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

23 投票
6 回答
42886 浏览
提问于 2025-04-16 23:28

我有一个Python脚本,运行起来需要很长时间。我想在命令行输出中加一个小小的“等待”动画,就像浏览器在处理AJAX请求时显示的旋转圆圈那样。具体来说,就是输出一个'\',然后换成'|',再换成'/',接着是'-',再回到'|',这样文字就像在转圈一样。我不太确定在Python中怎么替换之前打印的文本。

6 个回答

6

这是一个加载条,适合在你安装某些东西的时候使用。

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
12

又一个漂亮的变体

import time

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

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

使用 \r 和不换行打印(也就是在后面加个逗号):

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

对于 Python 2,使用这个 print 语法:

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

撰写回答