使用python多处理模块创建的子进程将无法打印

问题描述:

我对下面的代码以及在子进程中使用print函数的任何代码有问题.即使使用sys.std[err|out].write('worker')而不是print,我也看不到任何打印的语句.

I have a problem with the code below, and with any code that uses the print function in the child processes. I can't see any printed statements, even if I use sys.std[err|out].write('worker') instead of print.

这是代码(来自官方python文档的 ):

This is the code (from the official python documentation):

from multiprocessing import Process

def f(name):
    print 'hello', name

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

输出为空白.

注意:以下代码使用线程模块并打印输出:

Note: The following code uses the threading module and it prints the output:

import threading

def f(name):
    print 'hello', name

if __name__ == '__main__':
    p = threading.Thread(target=f, args=('bob',))
    p.start()
    p.join()

输出:hello bob

能否请您指出解决方案?预先感谢.

Can you please point me to the solution? Thanks in advance.

尝试一下:

from multiprocessing import Process
import sys

def f(name):
    print 'hello', name
    sys.stdout.flush()

...

AFAIK缓冲了由multiprocessing模块生成的已处理标准输出,因此,只有在缓冲区已满或显式刷新sys.stdout时,您才可以看到输出.

AFAIK the standard output of processed spawned by the multiprocessing module is buffered, hence you will see the output only if the buffer becomes full or you explicitly flush sys.stdout.