Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Waiting' animation in command prompt (Python)

Tags:

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.

like image 403
Sarah Avatar asked Aug 12 '11 10:08

Sarah


People also ask

Can you code animation with Python?

You can create animations in Python by calling a plot function inside of a loop (usually a for-loop). The main tools for making animations in Python is the matplotlib. animation. Animation base class, which provides a framework around which the animation functionality is built.


2 Answers

Use \r and print-without-newline (that is, suffix with a comma):

animation = "|/-\\"
idx = 0
while thing_not_complete():
    print(animation[idx % len(animation)], end="\r")
    idx += 1
    time.sleep(0.1)

For Python 2, use this print syntax:

print animation[idx % len(animation)] + "\r",
like image 163
AKX Avatar answered Sep 26 '22 17:09

AKX


Just another pretty variant

import time

bar = [
    " [=     ]",
    " [ =    ]",
    " [  =   ]",
    " [   =  ]",
    " [    = ]",
    " [     =]",
    " [    = ]",
    " [   =  ]",
    " [  =   ]",
    " [ =    ]",
]
i = 0

while True:
    print(bar[i % len(bar)], end="\r")
    time.sleep(.2)
    i += 1
like image 42
LPby Avatar answered Sep 23 '22 17:09

LPby