简体   繁体   English

在多处理过程中抑制输出

[英]Suppress output in multiprocessing process

I have some code which runs in parallel using the multiprocessing Pool class. 我有一些使用multiprocessing Pool类并行运行的代码。 Unfortunately some of the functions I use from another library have some verbose output. 不幸的是,我在另一个库中使用的某些功能有一些冗长的输出。 To abstract the problem have a look at the following example: 要抽象问题,请看以下示例:

from multiprocessing import Pool

def f(x):
    print 'hello'
    return x*x

p = Pool(10)
p.map(f, [1,2,3])

So this will print 'hello' like 10 times. 因此,这将打印出“ hello”之类的10次。 Is there a possibility to mute the output of the processes or to put the std.out in some variable? 是否有可能使进程的输出静音或将std.out放入某些变量中? Thanks for any suggestion. 感谢您的任何建议。

EDIT: I don't want to redirect the whole stdout, just for the processes of my pool. 编辑:我不想重定向整个标准输出,只是为了我的池的过程。

Use the initializer parameter to call mute in the worker processes: 使用initializer参数在工作进程中调用mute

import sys
import os
from multiprocessing import Pool

def mute():
    sys.stdout = open(os.devnull, 'w')    

def f(x):
    print 'hello'
    return x*x

if __name__ == '__main__':
    p = Pool(10, initializer=mute)
    p.map(f, [1,2,3])
    print('Hello')

prints 版画

Hello

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM