如何为多线程Python脚本共享标准输出?

8

我正在编写一个脚本,其中有5个线程,我希望共享/重定向所有线程的stdout,以正确获取所有输出。

我已尝试以下代码,但没有起作用,有人可以帮忙吗?

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()
2个回答

10

不要重定向stdout(此方法无法重定向stderr),你也可以使用Python logging模块。

然后,您可以使用logging.info("message")替换print语句。

logging模块提供了很多可能性,比如打印哪个线程发布了消息等。


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的这个答案中找到一个类似的实现来处理这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接