Home > Back-end >  How to refresh an stdout in python
How to refresh an stdout in python

Time:12-25

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

CodePudding user response:

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?

  • Related