Question

Unfortunately I am limited to Python 2.4 and am looking to have an ascii animation run while my script performs (ie a spinning circle) I'm just wondering what the common methodology or practice is for doing something like this and any/all resources in relation to the solution, example scripts would be awesome!! I've been using os.sytem('command') and want to get out of the habit.

Thanks!!

Was it helpful?

Solution

One possible way to do this is to use the carriage return character "\r" to return the cursor to the beginning of the line, so you can overwrite previously written characters. This allows you to create animations, as long as it fits on the current line. For example:

import time

def do_a_little_work():
    time.sleep(0.1)

print "about to do work..."

icons = ["-", "/", "|", "\\"]
icon_idx = 0

while True:
    do_a_little_work()
    #todo: check if work is done, and break out of the loop.
    print "\r" + icons[icon_idx],
    icon_idx = (icon_idx+1)%len(icons)

print "\rdone."

Result:

about to do work...
-

Which becomes

about to do work...
/

Which becomes

about to do work...
|

Which becomes

about to do work...
\

etc... Finally becoming

about to do work...
done.

enter image description here


You can use threading to run your animation simultaneously with your regular code.

from threading import Thread
import time

def do_the_work():
    #execute your script here

work_thread = Thread(target=do_the_work)
print "Working..."
work_thread.start()

icons = ["-", "/", "|", "\\"]
icon_idx = 0
while work_thread.is_alive():
    time.sleep(0.1)
    print "\r" + icons[icon_idx],
    icon_idx = (icon_idx+1)%len(icons)
print "\rdone"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top