命令提示符中的'等待'动画(Python)

时间:2011-08-12 10:56:33

标签: python animation command

我有一个需要很长时间才能运行的Python脚本。我非常希望让命令行输出有一些“等待”动画,就像我们在浏览器中获取的AJAX请求的旋转圆圈一样。类似于'\'的输出,然后将其替换为'|',然后是'/',然后是' - ','|'等,就像文本在圆圈中一样。我不知道如何用Python替换以前的印刷文本。

4 个答案:

答案 0 :(得分:19)

使用\r和print-without-newline(即带逗号的后缀):

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

对于Python 3,请使用此print语法:

print(animation[idx % len(animation)], end="\r")

答案 1 :(得分:1)

一个加载栏,对于您要安装的东西很有用。

animation = [
"[        ]",
"[=       ]",
"[===     ]",
"[====    ]",
"[=====   ]",
"[======  ]",
"[======= ]",
"[========]",
"[ =======]",
"[  ======]",
"[   =====]",
"[    ====]",
"[     ===]",
"[      ==]",
"[       =]",
"[        ]",
"[        ]"
]

notcomplete = True

i = 0

while notcomplete:
    print(animation[i % len(animation)], end='\r')
    time.sleep(.1)
    i += 1

如果要持续几秒钟,请

if i == 17*10:
    break

之后

i += 1

答案 2 :(得分:0)

另一个漂亮的变体

import time

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

while True:
    print(bar[i % len(bar)], end="\r")
    time.sleep(.2)
    i += 1

答案 3 :(得分:-1)

Python的内置curses包中包含用于控制打印到终端屏幕的内容的实用程序。