python子进程的输出不可见_在python中访问子进程的标准输出

How can I access the stdout of child processes prior to sending them to main process? I am using multiprocessing.Pool module to generate child process pools.

解决方案

The main process and the children all share the same standard input and standard output file descriptors. They have no control over what the other writes to them. The only thing you can do is replace stdin and stdout in the children with something else that the main process can control. As an example you could subclass a dummy file object like StringIO and redirect the data that the children write to this object to the parent via a Queue:

import sys

from multiprocessing import Queue, Pool, current_process

from StringIO import StringIO

class MyStringIO(StringIO):

def __init__(self, queue, *args, **kwargs):

StringIO.__init__(self, *args, **kwargs)

self.queue = queue

def flush(self):

self.queue.put((current_process().name, self.getvalue()))

self.truncate(0)

def initializer(queue):

sys.stderr = sys.stdout = MyStringIO(queue)

def task(num):

print num

sys.stdout.flush()

return num ** 2

q = Queue()

pool = Pool(3, initializer, [q])

for _ in pool.map(task, range(5)):

proc, out = q.get()

print proc, "got", out

This should print something like this:

PoolWorker-1 got 0

PoolWorker-1 got 3

PoolWorker-1 got 4

PoolWorker-2 got 1

PoolWorker-3 got 2

Don't forget to call sys.{stdout,stderr}.flush() at the end of task otherwise, nothing will be written to the queue.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值