Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 628
spacegoing Avatar asked Jan 09 '16 05:01

spacegoing


1 Answers

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.

like image 172
Jorge Torres Avatar answered Oct 01 '22 18:10

Jorge Torres