1

I'm trying to make a loading progress bar, but I get something like this when I run my code:

[          ] 0%
[=         ] 10%
[==        ] 20%
[===       ] 30%
[====      ] 40%
[=====     ] 50%
[======    ] 60%
[=======   ] 70%
[========  ] 80%
[========= ] 90%
[==========] 100%

When I expected something like this:

[          ] 0%
<Later>
[=         ] 10%
<Even Later>
[==        ] 20%
<And you get the idea>

It's supposed to clear the previous line every time it prints a new one. I've tried everything I found on Google, but it wasn't much help. I tried using "\r", but I get this:

[          ] 0%

[=         ] 10%

[==        ] 20%

[===       ] 30%

[====      ] 40%

[=====     ] 50%

[======    ] 60%

[=======   ] 70%

[========  ] 80%

[========= ] 90%

[==========] 100%

Here's my code:

import time
import random
for p in range(0, 11):
   print("[" + ("="*p) + (" "*(10-p)) + "] " + str(p*10)+"%")
   time.sleep(random.uniform(0.1, 1))

Can someone help find a way to clear the whole output console?

2 Answers 2

1

Use end='\r' as argument to print function:

print("[" + ("="*p) + (" "*(10-p)) + "] " + str(p*10)+"%", end='\r')

...which prints all your output in one line replacing the previous output.

Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't work. Gives me this: [ ] 0%[= ] 10%[== ] 20%[=== ] 30%[==== ] 40%[===== ] 50%[====== ] 60%[======= ] 70%[======== ] 80%[========= ] 90%[==========] 100%
It would run if you run this in CLI. Navigate to the directory your python file is and type python yourfilename.py
0

If you are not working with Python notebook and '\r' is not working for you you can use the ASCII escape sequence

import time
import random
import sys
for p in range(0, 11):
    sys.stdout.write("\033[F")
    print("\r"+"[" + ("="*p) + (" "*(10-p)) + "] " + str(p*10)+"%")
    time.sleep(random.uniform(0.1, 1))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.