I'm writing a progress bar as this How to animate the command line? suggests. I use Pycharm and run this file in Run Tool Window.
import time
def show_Remaining_Time(time_delta):
print('Time Remaining: %d' % time_delta, end='\r', flush=True)
if __name__ == '__main__':
count = 0
while True:
show_Remaining_Time(count)
count += 1
time.sleep(1)
However, the code displays nothing if I run this .py file. What am I doing wrong?
I tried Jogger's suggest but it's still not working if I use print
function.
However the following script works as expected.
import time
import sys
def show_Remaining_Time(time_delta):
sys.stdout.write('\rtime: %d' % time_delta) # Doesn't work if I use 'time: %d\r'
sys.stdout.flush()
if __name__ == '__main__':
count = 0
while True:
show_Remaining_Time(count)
count += 1
time.sleep(1)
I have 2 questions now:
Why stdout works but print() not.
Why the How to animate the command line? suggests append \r
to the end while I have to write it at the start in my case?
The problem is that the '\r' at the end clears the line that you just printed, what about?
import time
def show_Remaining_Time(time_delta):
print("\r", end='')
print('Time Remaining: %d' % time_delta, end='', flush=True)
if __name__ == '__main__':
count = 0
while True:
show_Remaining_Time(count)
count += 1
time.sleep(1)
In this way, you clear the line first, and then print the desired display, keeping it in screen for the duration of the sleep.
NOTE: The code above was modified to add the end=''
as suggested in the comments for the code to work properly in some platforms. Thanks to other readers for helping to craft a more complete answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With