pythonstringprintingoverwrite

python: multiple print lines to be overwritten


Sorry for the noob question, I checked out other similar questions on the website but couldn't find one that solves my problem.

I'm very new to python so forgive me. I'm trying to make a bot which shows results of my trading account.

First step I would like to be able to see results in the terminal. Second step will be "writing those results on a webpage"

what i would like to achieve is that every single line of print get updated with new values on the same original lines.

the portion code of the function is this:

def eth_results():
    eth = s.get_wallet_balance()['result']['ETH']
    eth_starting_balance = 0.05015276
    eth_balance = eth['wallet_balance']
    eth_equity = eth['equity']
    eth_daily_pnl = format(eth['realised_pnl'],'.8f')
    eth_percentage_pnl = eth_starting_balance * (eth_starting_balance / (eth_balance - eth_starting_balance))
    print('\n--------------------------------------\n')
    print(f'Coin: ETHEREUM')
    print(f'Balance: {eth_balance}')
    print(f'Starting Balance: {eth_starting_balance}')
    print(f'Total Profit: {eth_percentage_pnl}')
    print(f'Total Equity: {eth_equity}')
    print('\n--------------------------------------\n')

then I'm telling it to repeat each 5 seconds

while True:
  eth_results()
  time.sleep(5)

right now the output is like this but i would like to have the results printed in the same lines, updating just the variables:

--------------------------------------

Coin: ETHEREUM
Balance: 0.0513822
Starting Balance: 0.05015276
Total Profit: 2.0458902716827083
Total Equity: 0.05133733

--------------------------------------


--------------------------------------

Coin: ETHEREUM
Balance: 0.0513822
Starting Balance: 0.05015276
Total Profit: 2.0458902716827083
Total Equity: 0.05133754

--------------------------------------


--------------------------------------

Coin: ETHEREUM
Balance: 0.0513822
Starting Balance: 0.05015276
Total Profit: 2.0458902716827083
Total Equity: 0.05133706

--------------------------------------

but I can't achieve it. If i use the \r only the last line will be replaced. Basically I would like to replace ALL the lines. I'm pretty sure there are multiple ways to achieve this, and multiple ways to "clean the code" but right now I'm just willing to find ANY "working solution" rather than finding "the only best way" to do it. Of course I'm willing to code in a better way when I'll gain more experience.

BONUS: after that I would also like to basically print (and ovewrite) the same thing on a text/html/whatever kind of file. But this is not the priority now.

Thanks a lot


Solution

  • You can print a bunch of new lines to clear the console.

    clear = "\n" * 100
    print(clear)
    

    You cannot overwrite an already printed line in the console since it is an output.