[英]Redirecting stdout to multiprocessing.Pipe throws error
I would like to redirect stdout
and stderr
of a new process back to the parent process via pipe. 我想通过管道将新进程的stdout
和stderr
重定向回父进程。
I have found this code in another thread , which uses the os.dup2()
function to duplicate stdout
. 我在另一个线程中找到了此代码, 该线程使用os.dup2()
函数复制stdout
。
import os
from multiprocessing import Process, Pipe
def spam(w):
os.dup2(w.fileno(), 1)
for i in range(3):
print('eggs')
if __name__ == '__main__':
r, w = Pipe()
reader = os.fdopen(r.fileno(), 'r')
p = Process(target=spam, args=(w,))
p.start()
for i in range(3):
print('From pipe: %s' % reader.readline())
reader.close()
p.join()
With Python 2.7 everything works fine, but Python 3 gives me a invalid file descriptor error after the main process has read the messages from the pipe. 使用Python 2.7,一切正常,但是在主进程从管道读取消息后,Python 3给我一个无效的文件描述符错误。 I cannot figure out why this happens. 我不知道为什么会这样。 I tried closing the file handler explicitly, but it did not work. 我尝试显式关闭文件处理程序,但是没有用。
(I'm running this on a Linux machine.) (我正在Linux机器上运行它。)
So, as it turns out not closing reader
works fine. 因此,事实证明不关闭reader
效果很好。
import os
from multiprocessing import Process, Pipe
def spam(w):
os.dup2(w.fileno(), 1)
for i in range(3):
print('eggs')
if __name__ == '__main__':
r, w = Pipe()
reader = os.fdopen(r.fileno(), 'r')
p = Process(target=spam, args=(w,))
p.start()
for i in range(3):
print('From pipe: %s' % reader.readline())
p.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.