蟒蛇:运行陆侃酒吧,同时工作吗?(Python: Run a progess bar and wor

2019-07-04 02:33发布

我想知道如何同时运行一个进度条和一些其他工作,那么当工作完成后,停止在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!"

Answer 1:

你可以在运行使用后台线程的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()


Answer 2:

你可以创建一个显示进度条单独的线程。 这可以实现,如图@ 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!")


文章来源: Python: Run a progess bar and work simultaneously?