【问题标题】:How to share stdout for multi-threaded python script?如何为多线程 python 脚本共享标准输出?
【发布时间】:2015-06-30 11:49:21
【问题描述】:
我正在编写一个有 5 个线程的脚本,我想为所有线程共享/重定向标准输出,以正确获取所有打印。
我试过下面的代码,但它不起作用,有人可以帮忙吗?
class Logwriter():
def __init__(self):
self.terminal = sys.stdout
def write(self,message):
lock = threading.Lock()
lock.acquire()
self.terminal.write(message)
lock.release()
sys.stdout=Logwriter()
【问题讨论】:
标签:
python
multithreading
【解决方案1】:
您也可以使用 python logging 模块,而不是重定向 stdout(它不会提供 stderr 的重定向)。
然后你可以用 logging.info("message") 替换你的打印语句。
日志模块提供了很多可能性,比如打印哪个线程发布了一条消息等。
【解决方案2】:
在__init__ 方法中实例化一个锁,并将其与write 方法中的with 语句一起使用:
class Logwriter():
def __init__(self):
self.terminal = sys.stdout
self.lock = threading.Lock()
def write(self,message):
with self.lock:
self.terminal.write(message)
另外,这也不起作用,因为print "hello" 先调用sys.stdout.write("hello"),然后再调用sys.stdout.write("\n")。
您会在 Alex Martelli 的 this answer 中找到处理该问题的类似实现。