我有一段 python 代码可以监听子进程发送的消息。消息可以是直接打印到控制台窗口的普通字符串,也可以是带有异常对象和回溯输出的元组,将在程序的其他地方处理。multiprocessing.Queue 实现用于进程间通信。队列对象由 self.channel 引用。
while self.exp_process.is_alive() or not self.channel.empty():
# Make sure Qt interface stays responsive, gets redrawn, etc.
QtGui.QApplication.processEvents()
# Check if messages are pending to be processed
# Sleep otherwise
if not self.channel.empty():
# Encapsulated by print statements for debugging of None print
print "Retrieving message"
msg = self.channel.get(False)
print "Message received"
# Directly print received strings
if type(msg) in [str, unicode]:
sys.stdout.write(msg)
# Errors arrive as a tuple with (Error object, traceback)
elif type(msg) == tuple and isinstance(msg[0], Exception):
return msg
else:
sys.stderr.write(u"Illegal message type received from child process")
else:
time.sleep(0.1)
当 msg 是一个元组(包含来自子进程的错误信息)时,
msg = self.channel.get(False)
似乎打印无,因为控制台中的输出是
Retrieving message
None
Message received
在此之后,msg 包含的元组被按原样处理,表明收到了正确的信息。接收元组时,似乎 None 被打印在 Queue.get() 函数内的某处。有没有办法抑制它的输出,或者解决这个问题?