[英]How to share stdout for multi-threaded python script?
I am writing a script which has 5 threads, i want to share/redirect stdout for all the thread, to get all prints properly. 我正在写一个有5个线程的脚本,我想为所有线程共享/重定向stdout,以正确获取所有打印。 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()
Instead of redirecting stdout (which won't provide redirection of stderr btw), you could also use the python logging module. 您也可以使用python 日志记录模块,而不是重定向stdout(不会提供stderr btw的重定向)。
Then you can replace your print statements with logging.info("message"). 然后,您可以使用logging.info(“message”)替换print语句。
The logging module provides a lot of possibilities like printing which thread posted a message etc. 日志记录模块提供了很多可能性,例如打印哪个帖子发布了消息等。
Instantiate a lock in the __init__
method and use it with a with
statement in the write
method: 在__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)
Also, this won't work because print "hello"
calls sys.stdout.write("hello")
first, then sys.stdout.write("\\n")
. 此外,这将无法工作,因为print "hello"
调用sys.stdout.write("hello")
,然后调用sys.stdout.write("\\n")
。
You'll find a similar implementation that handles that issue in this answer by Alex Martelli. 您将在Alex Martelli的回答中找到类似的实现来处理该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.