python:multiprocessing.Pipe和重定向标准输出 [英] python: multiprocessing.Pipe and redirecting stdout

查看:579
本文介绍了python:multiprocessing.Pipe和重定向标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用multiprocessing包产生第二个进程,我想从中将stdout和stderr重定向到第一个进程.我正在使用multiprocessing.Pipe对象:

I am using multiprocessing package to spawn a second process from which I would like to redirect stdout and stderr into the first process. I am using multiprocessing.Pipe object:

dup2(output_pipe.fileno(), 1)

其中output_pipemultiprocessing.Pipe的实例.但是,当我尝试另一端阅读时,它只是挂起了.我尝试使用Pipe.recv_bytes进行读取,但有限制,但会引发OSError.完全有可能吗?还是我应该切换到一些较低级别的管道功能?

Where output_pipe is an instance of multiprocessing.Pipe. However, when I try to read on the other end, it just hangs. I tried reading using Pipe.recv_bytes with a limit, but that raises an OSError. Is this possible at all or should I just switch to some lower level pipe functions?

推荐答案

在Python 2.7中进行实验后,我得到了这个工作示例.使用os.dup2管道的文件描述符被复制到标准输出文件描述符,并且每个print函数最终都写入管道.

After experimenting in Python 2.7 I got this working example. With os.dup2 pipe's file descriptor is copied to standard output file descriptor, and each print function ends up writing to a pipe.

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!

这篇关于python:multiprocessing.Pipe和重定向标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆