本文介绍了Python:运行进度栏并同时工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何同时运行进度条和其他一些工作,然后在完成工作后,在Python(2.7.x)中停止进度条

I want to know how to run a progress bar and some other work simultaneously, then when the work is done, stop the progress bar in 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*

我将如何做类似的事情:

How would I be able to do something like:

progress_bar() #run in background?
work()
*stop progress bar*
print "\nThe work is done!"

推荐答案

您可以使用 threading模块.例如:

You could run a thread in the background using the threading module. For example:

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:运行进度栏并同时工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:26
查看更多