命令提示符中的“等待”动画(Python) [英] 'Waiting' animation in command prompt (Python)
问题描述
我有一个需要很长时间才能运行的Python脚本。我很想让命令行输出有一点等待中的动画,就像我们在浏览器中看到的用于AJAX请求的漩涡形圆圈一样。类似于 \的输出,然后将其替换为 |,然后是 /,然后是-, |,等等,就像文本在转一圈一样。我不确定如何替换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.
推荐答案
使用 \r
和不带换行符的打印(即后缀带逗号):
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)
对于Python 2,请使用 print
语法:
For Python 2, use this print
syntax:
print animation[idx % len(animation)] + "\r",
这篇关于命令提示符中的“等待”动画(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!