Python:运行进度栏并同时工作?
问题内容:
我想知道如何同时运行进度条和其他一些工作,然后当工作完成后,在Python(2.7.x)中停止进度条
import sys, time
def progress_bar():
while True:
for c in ['-','\\','|','/']:
sys.stdout.write('\r' + "Working " + c)
sys.stdout.flush()
time.sleep(0.2)
def work():
*doing hard work*
我将如何做类似的事情:
progress_bar() #run in background?
work()
*stop progress bar*
print "\nThe work is done!"
问题答案:
你可以在运行使用后台线程的threading
模块。例如:
def run_progress_bar(finished_event):
chars = itertools.cycle(r'-\|/')
while not finished_event.is_set():
sys.stdout.write('\rWorking ' + next(chars))
sys.stdout.flush()
finished_event.wait(0.2)
# somewhere else...
finished_event = threading.Event()
progress_bar_thread = threading.Thread(target=run_progress_bar, args=(finished_event,))
progress_bar_thread.start()
# do stuff
finished_event.set()
progress_bar_thread.join()