Python3: print (somestring, end = '\ r', flush = True) shows nothing

I am writing a progress bar, as shown How to animate the command line? . I use Pycharm and run this file in the 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, if I run this .py file, the code does not display anything. What am I doing wrong?


I tried Jogger, but it still does not work if I use the 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:

  • Why stdout works, but print () doesn't.

  • Why How to animate the command line? suggests adding \r to the end, while I have to write it at the beginning in my case?

+5
source share
2 answers

The problem is that the '\ r' at the end clears the line you just printed, so what?

 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) 

Thus, first you clear the line, and then print the screen you want, keeping it on the screen for the entire time you sleep.

NOTE. The code above has been modified to add end='' , as indicated in the comments, for the code to work correctly on some platforms. Thanks to other readers for helping to develop a more complete answer.

+2
source

This method can print on the same command line:

 import time def show_Remaining_Time(time_delta): print(' \r%d:Time Remaining' % time_delta, end = '',flush=False) if __name__ == '__main__': count = 0 while True and count < 10: show_Remaining_Time(count) count += 1 time.sleep(1) 
0
source

Source: https://habr.com/ru/post/1240219/


All Articles