您可以创建一个单独的线程来显示进度条。这可以如@icktoofay 的回答中所示完成,但是我更喜欢下面的实现,它为任务派生一个新的线程子类。这种方法的一个优点是所有内容都包含在新类的每个实例中,因此您不需要全局变量来进行它们与主线程之间的通信。
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!")