My script will run for a few hours and I want to be updated on its status. I usually use sys.stdout.write("\r"+string)
and it works quite well but currently, I need to log multiple things, so I will have to use '\n'
or add another print function.
I'm running out of ideas. I was playing around with curses
but it can't find PyCharm's console when initscr()
.
So, how do you flush a multiline output?
Dummy code:
import sys
import time
for i in range(2):
# sys.stdout.write(
# "\r"+
# "line 1 loop {loop1}\n"
# "line 2 loop {loop2}\n".format(
# loop1=i,
# loop2=i
# ))
sys.stdout.write("\r" + "line 3 loop {loop}".format(loop=i))
sys.stdout.write("\r" + "line 4 loop {loop}".format(loop=i))
# sys.stdout.write("line 6 loop {loop}\n".format(loop=i))
# sys.stdout.write("line 7 loop {loop}\n".format(loop=i))
# sys.stdout.flush()
# print("line 5 loop {loop}".format(loop=i), end="\r", flush=True)
time.sleep(0.5)
Outputs:
line 4 loop 1
Desired output:
line 3 loop 1
line 4 loop 1
UPDATED since my example wasn't clear enough
import sys
import time
def increment(i):
return i+1
def multiply(i):
return i*2
for i in range(5):
sys.stdout.write(
"\r"+
"candies eaten {candies}\n"
"chocolates eaten {chocolate}\n".format(
candies=increment(i),
chocolate=multiply(i)
))
time.sleep(0.5)
Outputs
candies eaten 1
chocolate eaten 0
candies eaten 2
chocolate eaten 2
candies eaten 3
chocolate eaten 4
candies eaten 4
chocolate eaten 6
candies eaten 5
chocolate eaten 8
Desired output
candies eaten 5
chocolate eaten 8
updated with each loop.