我正在编写一个包含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()
答案 0 :(得分:5)
您可以使用python logging模块,而不是重定向stdout(它不会提供stderr btw的重定向)。
然后你可以用logging.info替换你的print语句(" message")。
日志记录模块提供了很多可能性,比如打印哪个帖子发布了消息等。
答案 1 :(得分:1)
在__init__
方法中实例化锁定,并将其与with
方法中的write
语句一起使用:
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处理这个问题。