PyCharm Python Console - printing on the same line that does not work as intended

My goal is to show the download progress in my console, overwriting the previous line with the current progress. I found many solutions for Python version 3, but they do not work.

For example:

import time for i in range(10): print(i, end='', flush=True) time.sleep(1) 

Gives me the following result:

 0123456789 

Or both:

 import time for i in range(10): print(i, end='\r', flush=True) time.sleep(1) 

and:

 import time for i in range(10): print("\b" + str(i), end='', flush=True) time.sleep(1) 

Gives me the following result:

 0 1 2 3 ... 

Any idea? I work in PyCharm Community Edition with the Anaconda package.

Many thanks!

EDIT: The problem does not occur when I run the python file (using PyCharm), but only when I execute "Performing a selection in the console"

+3
python console pycharm
source share
1 answer

You need to gain control over writing on stdout and clear it. So the link given by ma3oun matters. Unfortunatelly The PyCharm console works differently than on the command line. The question of how this works should be directed to the PyCharm team, and Mine will ask them to change this behavior.

In any case, the solution to your problem is to add \ r before writing:

 import sys import time for i in range(10): sys.stdout.write("\r{0}".format(str(i))) sys.stdout.flush() time.sleep(1) 

However, for shorter sleep times (for example, 0.1), there is a problem with short-term buffer flushing. For each flush you get more than one write value. As a workaround, I found that you can add another such file:

 for i in range(10): sys.stdout.write("\r \r {0}".format(str(i))) sys.stdout.flush() time.sleep(0.1) 

This will force the console to display only one record value, but you will lose some values ​​between the display, because it looks like the update is updating slower than 0.1 seconds.

My solution for a progress banner that displays correctly in the PyCharm console:

 import sys import time progressVis = {0: ' ', 1: '- ', 2: '-- ', 3: '--- ', 4: '---- ', 5: '----- ', 6: '------ ', 7: '------- ', 8: '-------- ', 9: '--------- ', 10: '----------'} size = 20 for i in range(0, size): percent = int((float(i + 1) / size) * 10) str1 = "\r \r [{0}] {1}/{2} {3}%".format(progressVis[percent], i + 1, size, ((i + 1) * 100 / size)) sys.stdout.write(str1) sys.stdout.flush() time.sleep(0.1) 
+5
source share

All Articles