Python:运行一个progess栏并同时工作?
作者:互联网
我想知道如何同时运行进度条和其他一些工作,然后在工作完成后,停止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!"
解决方法:
您可以使用the threading
module在后台运行一个线程.例如:
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()
标签:python,progress-bar,multitasking 来源: https://codeday.me/bug/20190716/1479912.html