不幸的是我只限于Python 2.4并希望在我的脚本执行时运行ascii动画(即一个旋转的圆圈)我只是想知道做这样的事情和任何/所有的常见方法或实践是什么与解决方案相关的资源,示例脚本会很棒!!我一直在使用os.sytem('命令')并希望摆脱这种习惯。
谢谢!
答案 0 :(得分:3)
一种可能的方法是使用回车符“\ _”将光标返回到行的开头,这样就可以覆盖以前写入的字符。这允许您创建动画,只要它适合当前行。例如:
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."
结果:
about to do work...
-
哪个成为
about to do work...
/
哪个成为
about to do work...
|
哪个成为
about to do work...
\
等等......最后成为
about to do work...
done.
您可以使用threading
与常规代码同时运行动画。
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"