PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 18, 2022

[FIXED] How to refresh an stdout in python

 September 18, 2022     printing, python, python-3.x, stdout, sys     No comments   

Issue

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


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?



Answered By - Yevhen Bondar
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing