【发布时间】:2016-05-24 19:06:56
【问题描述】:
Python 2.6.6
我有一个要执行的线程列表,主代码将等待 (Threading.join()) 直到它们全部完成。
>>> for thread in threadList:
... thread.start()
>>> for t in threadList:
... t.join()
有没有办法在主代码等待线程结束时打印诸如“正在运行...”之类的消息?
我想一秒又一秒地打印相同的东西(“正在运行...”),直到线程全部完成。
谢谢。
已解决
实施的解决方案:
>>> for thread in threadList:
... thread.start()
>>> string = "running"
>>> while any(t.is_alive() for t in threadList):
... sys.stdout.write("\r%s" % string)
... sys.stdout.flush()
... string = string + "." #this may not be the best way
... time.sleep(0.5)
在我的情况下,“time.sleep(0.5)”的额外时间不是问题,尽管它不是最推荐的。
这会生成输出:
running........
“running”之后的点将一个接一个地打印在同一行,同时还有任何线程处于活动状态。果然如我所料!
基于@Manuel Jacob 和@Alex Hall 的回答。
【问题讨论】:
标签: python multithreading