如何为多线程python脚本共享stdout? [英] How to share stdout for multi-threaded python script?

查看:292
本文介绍了如何为多线程python脚本共享stdout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个具有5个线程的脚本,我想为所有线程共享/重定向标准输出,以正确获取所有打印件. 我已经尝试使用以下代码,但无法正常工作,有人可以帮忙吗?

I am writing a script which has 5 threads, i want to share/redirect stdout for all the thread, to get all prints properly. I have tried with the below code but its not working, can anybody help?

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

Instead of redirecting stdout (which won't provide redirection of stderr btw), you could also use the python logging module.

然后,您可以将打印语句替换为logging.info("message").

Then you can replace your print statements with logging.info("message").

日志记录模块提供了很多可能性,例如打印哪个线程发布了一条消息等.

The logging module provides a lot of possibilities like printing which thread posted a message etc.

这篇关于如何为多线程python脚本共享stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆