Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to refresh an stdout in python

Hello and thank you in advance for your help,
In fact I have a progress bar with various options that I would have liked to see refreshed instead of spending my time clearing the console.

while True :
    #system("cls")
    sys.stdout.write("\rSearching for {} --- [Currently {} found] \nLoading [".format(entry, count_result) + "="*int(100 * count / nb_files) + " "*(100-int(100 * count / nb_files)) + "] {}%".format(int(round(float(int(100 * count / nb_files))))) + "\n")
    sys.stdout.flush()
    sleep(0.5)
    if int(100 * count / nb_files) == 100 :
        sleep(1)
        system("cls")
        break

So I would have liked to know if there was a way, I looked everywhere to try to understand but I do not understand how I could do it in my case. thanks in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The easiest way to "refresh" progress bar is print line without LF (\n) a new symbol. Instead you you just CR (\r) carriage return symbol. With this approach cursor will return to the same line and rewrite it

import sys
import time

for i in range(100):
    print("Progress: {}% ".format(i), end="\r")
    time.sleep(.1)

The main downside of this approach, that it leaves symbols from the previous line. You can see it with this example.

import sys
import time

for i in range(100):
    print("Progress: {}% ".format(i), end="\r")
    time.sleep(.5)
    print("short line", end="\r")
    time.sleep(.5)

So, you should also clean line before you write a new one

import sys
import time

for i in range(100):    
    print("                                                                     ", end="\r")
    print("Progress: {}% ".format(i), end="\r")
    time.sleep(.1)

Here more info about CR and LF symbols What are carriage return, linefeed, and form feed?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading