我想知道如何同时运行进度条和其他一些工作,然后在工作完成后,停止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!"
答案 0 :(得分:8)
您可以使用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()
答案 1 :(得分:4)
您可以创建一个显示进度条的单独线程。这可以像@ icktoofay的answer中所示完成,但是我更喜欢类似下面的实现,它为任务派生一个新的线程子类。这种方法的一个优点是所有内容都包含在新类的每个实例中,因此您不需要全局变量来进行它们与主线程之间的通信。
import sys
import threading
import time
class ProgressBarThread(threading.Thread):
def __init__(self, label='Working', delay=0.2):
super(ProgressBarThread, self).__init__()
self.label = label
self.delay = delay # interval between updates
self.running = False
def start(self):
self.running = True
super(ProgressBarThread, self).start()
def run(self):
label = '\r' + self.label + ' '
while self.running:
for c in ('-', '\\', '|', '/'):
sys.stdout.write(label + c)
sys.stdout.flush()
time.sleep(self.delay)
def stop(self):
self.running = False
self.join() # wait for run() method to terminate
sys.stdout.write('\r' + len(self.label)*' ' + '\r') # clean-up
sys.stdout.flush()
def work():
time.sleep(5) # *doing hard work*
pb_thread = ProgressBarThread('Computing')
pb_thread.start()
work()
pb_thread.stop()
print("The work is done!")