''Waiting' animation in command prompt (Python)
I have a Python script which takes a long time to run. I'd quite like to have the command line output to have a little 'waiting' animation, much like the swirly circle we get in browsers for AJAX requests. Something like an output of a '\', then this is replaced by a '|', then '/', then '-', '|', etc, like the text is going round in circles. I am not sure how to replace the previous printed text in Python.
Solution 1:[1]
Just another pretty variant
import time
bar = [
" [= ]",
" [ = ]",
" [ = ]",
" [ = ]",
" [ = ]",
" [ =]",
" [ = ]",
" [ = ]",
" [ = ]",
" [ = ]",
]
i = 0
while True:
print(bar[i % len(bar)], end="\r")
time.sleep(.2)
i += 1
Solution 2:[2]
A loading bar useful for if you're installing something.
animation = [
"[ ]",
"[= ]",
"[=== ]",
"[==== ]",
"[===== ]",
"[====== ]",
"[======= ]",
"[========]",
"[ =======]",
"[ ======]",
"[ =====]",
"[ ====]",
"[ ===]",
"[ ==]",
"[ =]",
"[ ]",
"[ ]"
]
notcomplete = True
i = 0
while notcomplete:
print(animation[i % len(animation)], end='\r')
time.sleep(.1)
i += 1
if you want to make it last a couple seconds do
if i == 17*10:
break
after the
i += 1
Solution 3:[3]
I think for best practices you can put a if condition at the end of the loop to avoid overflow with 'idx' variable:
import time
animation_sequence = "|/-\\"
idx = 0
while True:
print(animation_sequence[idx % len(animation_sequence)], end="\r")
idx += 1
time.sleep(0.1)
if idx == len(animation_sequence):
idx = 0
# Verify the change in idx variable
print(f' idx: {idx}', end='\r')
Solution 4:[4]
Python's built-in curses package contains utilities for controlling what is printed to a terminal screen.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LPby |
| Solution 2 | |
| Solution 3 | Pedro Felipe Bezerra |
| Solution 4 | adamnfish |
