0

I'm trying to make a progress meter that counts up until 100%, but I can't make it replace the line, instead it prints out: 0% 1% 2%

So how could I make it change using only one line?

This is my code:

x = range(101)
for n in x:
    timefluc = random.uniform(0, 1.2)
    time.sleep(timefluc)
    print("{0}%".format(n))

2 Answers2

2

By default, print adds a newline, '\n', after all arguments have been printed, moving you to the next line. Pass it end='\r' (carriage return) to make it return to the beginning of the current line without advancing to the next line. To be sure output isn't buffered (stdout is typically line buffered when connected to a terminal), make sure to pass flush=True to print as well, for a final result of:

for n in range(101):
    timefluc = random.uniform(0, 1.2)
    time.sleep(timefluc)
    print("{0}%".format(n), end='\r', flush=True)

Note that \r does not erase the line, so this only works because in your code, each new output is guaranteed to be at least as long as the previous line (and therefore will overwrite the entirety of the last line's data). If you might output a long line, then a short line, you'll need to make sure to pad all outputs with spaces sufficient to match or exceed the length of the longest possible line (without exceeding the terminal width).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • this doesnt work at least not in Sublime – gotiredofcoding Oct 25 '22 at 08:30
  • @gotiredofcoding: It relies on terminal support, and most IDE pseudo-terminals are (depending on how charitable you are) half-broken pieces of garbage or are intentionally not supporting `\r` to ensure you see all of your output to aid developers. Run your code in almost any "real" terminal and `\r` will reset the cursor back to the beginning of the current line. – ShadowRanger Oct 25 '22 at 10:58
0

That would depend on your terminal / console application, and there is no truly standard way, but you can try printing 'carriage return' character to go to beginning of the line:

x = range(101)
for n in x:
    timefluc = random.uniform(0, 1.2)
    time.sleep(timefluc)
    print("\r{0}%".format(n), end='')

Note the \r and also the usage of end='' argument.
\r is the "carriage return" that should return to beginning of line, and the end argument prevents print from going to the next line after printing the percentage.

Also you may want to use {0:3} for formatting which will keep the filed 3 characters long, automatically adding spaces on the left for padding, so that the percentage won't jump around as you go from 1% to 10% to 100%.

Lev M.
  • 6,088
  • 1
  • 10
  • 23