python:多处理.管道和重定向标准输出
我正在使用python:多处理.管道和重定向标准输出,python,multiprocessing,pipe,dup2,Python,Multiprocessing,Pipe,Dup2,我正在使用multiprocessing包生成第二个进程,我想从中将stdout和stderr重定向到第一个进程。我正在使用多处理.Pipe对象: dup2(output_pipe.fileno(), 1) 其中,output\u pipe是多处理.pipe的一个实例。然而,当我试图在另一端阅读时,它只是挂起。我尝试使用有限制的Pipe.recv_bytes进行读取,但这会引发OSError。这到底是可能的,还是应该切换到一些较低级别的管道函数?在Python 2.7中进行实验后,我得到了这个
multiprocessing
包生成第二个进程,我想从中将stdout和stderr重定向到第一个进程。我正在使用多处理.Pipe
对象:
dup2(output_pipe.fileno(), 1)
其中,
output\u pipe
是多处理.pipe
的一个实例。然而,当我试图在另一端阅读时,它只是挂起。我尝试使用有限制的Pipe.recv_bytes
进行读取,但这会引发OSError
。这到底是可能的,还是应该切换到一些较低级别的管道函数?在Python 2.7中进行实验后,我得到了这个工作示例。使用os.dup2
时,管道的文件描述符被复制到标准输出文件描述符,每个print
函数最后都会写入管道
import os
import multiprocessing
def tester_method(w):
os.dup2(w.fileno(), 1)
for i in range(3):
print 'This is a message!'
if __name__ == '__main__':
r, w = multiprocessing.Pipe()
reader = os.fdopen(r.fileno(), 'r')
process = multiprocessing.Process(None, tester_method, 'TESTER', (w,))
process.start()
for i in range(3):
print 'From pipe: %s' % reader.readline()
reader.close()
process.join()
输出:
From pipe: This is a message!
From pipe: This is a message!
From pipe: This is a message!
在Python2.7中进行实验后,我得到了这个工作示例。使用
os.dup2
时,管道的文件描述符被复制到标准输出文件描述符,每个print
函数最后都会写入管道
import os
import multiprocessing
def tester_method(w):
os.dup2(w.fileno(), 1)
for i in range(3):
print 'This is a message!'
if __name__ == '__main__':
r, w = multiprocessing.Pipe()
reader = os.fdopen(r.fileno(), 'r')
process = multiprocessing.Process(None, tester_method, 'TESTER', (w,))
process.start()
for i in range(3):
print 'From pipe: %s' % reader.readline()
reader.close()
process.join()
输出:
From pipe: This is a message!
From pipe: This is a message!
From pipe: This is a message!
您能否添加一个完整的、可运行的示例来演示您的错误?您能否添加一个完整的、可运行的示例来演示您的错误?您好,它确实可以工作,但是当从管道读取时:
r.recv()
它不能工作。您知道为什么,或者如何检查(非阻塞)读卡器是否有任何内容要读吗?@RadoslawGarbacz您必须使用w.send
,然后,根据。获取此错误-OSError:[Errno 9]os.fdopen语句的文件描述符不正确。你知道如何解决这个问题吗?注意-刚刚在Linux中试用过,这段代码可以工作,而同样的代码在Windows中失败-OSError:[Errno 9]错误的文件描述符我在Windows上试用过,它给OSError:[Errno 6]句柄无效。嗨,它确实可以工作,但是当从管道读取时:r.recv()
它不能工作。您知道为什么,或者如何检查(非阻塞)读卡器是否有任何内容要读吗?@RadoslawGarbacz您必须使用w.send
,然后,根据。获取此错误-OSError:[Errno 9]os.fdopen语句的文件描述符不正确。你知道如何解决这个问题吗?注意-刚刚在Linux中尝试过,这段代码可以工作,而同样的代码在Windows中失败-OSError:[Errno 9]错误的文件描述符我在Windows上尝试过,它给了OSError:[Errno 6]句柄无效。