Python Command Line Download Panel

I saw several different loading bars that are displayed in the terminal. However, some of them rely on \rone that doesn't seem to work, and maybe because I am using Python 2.7 instead of 3.X.

I have a loading bar, but every time it prints a new line.

def update_progress(progress):
    print"\r [{0}] {1}%".format('#'*(progress/10), progress)

while prog != 101:
    update_progress(prog)
    prog = prog + 1`

I am very new to Python, so if you can make the code short and clear if possible. This post may look like a duplicate question, but some of the others from Qaru are not working or are not printing on new lines.

If it \rshould work on Python 2.7, could you explain how to fix it since it does not work? However, this bothers me because it \nworks fine, but this is another problem.

PS: I also need to clear the line before printing.

Thanks AlwaysAwake

+4
source share
3 answers

Besides the fact that you never initialize prog(I suppose you want prog = 0before the loop while) you could suppress the printing of the newline character in Python2 by putting a comma after the statement

def update_progress(progress):
    print "\r [{0}] {1}%".format('#'*(progress//10), progress),

However, this comma is hard to miss when reading code, so it's best to import and use the Python 3 function print.

from __future__ import print_function

def update_progress(progress):
    print("\r [{0}] {1}%".format('#'*(progress//10), progress), end='')
+3
source

You need to use sys.stdout.write()it because it print()adds a new line:

import sys
def update_progress(progress):
    sys.stdout.write("\r [{0}] {1}%".format('#'*(progress/10), progress))

while prog != 101:
    update_progress(prog)
    prog = prog + 1

, python3 end print():

 print("\r [{0}] {1}%".format('#'*(progress/10), progress), end='')
0

sys.stdout.write("yourstring") sys.stdout.flush(), , . - Python termcolor colorama. , . , colorama termcolor , .

Python

Famecastle

0

All Articles