'Waiting' animation in command prompt (Python)

五迷三道 提交于 2020-05-07 18:34:46

问题


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.


回答1:


Use \r and print-without-newline (that is, suffix with a comma):

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

For Python 3, use this print syntax:

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



回答2:


Just another pretty variant

import time

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

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



回答3:


Python's built-in curses package contains utilities for controlling what is printed to a terminal screen.



来源:https://stackoverflow.com/questions/7039114/waiting-animation-in-command-prompt-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!