繁体   English   中英

如何从 Python 多处理进程打印?

[英]How can I print from a Python multiprocessing process?

编辑:对于那些后来发现这一点的人,这显然不是与某人链接到此的其他主题的重复。 该问题与标准输出缓冲无关,而是对 imap_unordered 如何调用do_something的误解

我正在尝试调试一个单独的问题,该问题需要我的 Python 多处理代码中的一些打印语句。 我可以在主进程中很好地打印(),但是当我产生新进程时,我无法成功打印任何东西。

这是我的问题的一个简单示例:

import argparse
from multiprocessing import Pool, get_context


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--foo', required=True)
    global args # need this if I'm reading from threads / forks
    args = parser.parse_args()

    print('This prints fine')
    with get_context('spawn').Pool(processes=4) as pool:
        pool.imap_unordered(do_something, [0, 1, 2, 3, 4 ])

    return

def do_something():
    print(args.foo * 2)
    print("this doesn't print either")

if __name__=="__main__":
    main()

do_something方法打印的正确方法是什么?

请注意,我在 Ubuntu 18.04 机器上使用来自 Bash 的 python。 没有使用 IDLE 或任何 IDE,我看到了类似的问题。

编辑:请注意,问题也不在于打印延迟,而是根本没有发生。 即使我刷新do_something function 中的标准输出缓冲区。

最终编辑:看起来我的代码实际上并没有调用do_something function。 当我强制它通过下面描述的方法时,我确实看到了预期的打印。 此代码生成 output:

import collections
from multiprocessing import Pool, get_context


def main():
    print('This prints fine')
    with get_context('spawn').Pool(processes=4) as pool:
        results = collections.deque(pool.imap_unordered(do_something, [0, 1, 2, 3, 4 ]), 0)

    print(results)
    return

def do_something(i):
    print("this doesn't print either") # Actually does print
    return i


if __name__=="__main__":
    main()

我说imap_unordered是懒惰的,虽然这是真的,但这实际上并不是您的代码无法运行的原因。 您的代码不会运行,因为没有什么会导致主进程在终止池之前等待池子进程完成。 with块退出时,池终止。 一个直接的等待方法是遍历imap_unordered的结果。

imap_unordered是懒惰的。 如此懒惰,事实上,它实际上还没有运行你的代码。 您需要对其进行迭代以检索其返回值。 这并不是您的程序的全部错误,但这至少应该让您继续前进!

这可能有点愚蠢,但我把它放在另一个代码中

import os
os.system('python "the_code_name &"')

他们都在两个过程中工作

暂无
暂无

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

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