简体   繁体   中英

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

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:

  1. Why stdout works but print() not.

  2. 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")
    print('Time Remaining: %d' % time_delta, 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.

This method can print in 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM