【发布时间】:2018-06-13 04:58:10
【问题描述】:
我最近开始研究多处理,因为我相信我的代码可以很容易地并行化。但是,在完成教程后,我遇到了一个问题:分布在池中的函数似乎无法打印。
这是罪魁祸首:
__spec__ = None # This line is required for Spyder and not part of the actual example
from multiprocessing import Process
import os
def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid())
print('process id:', os.getpid())
def f(name):
info('function f')
print('hello', name)
if __name__ == '__main__':
info('main line')
p = Process(target=f, args=('bob',))
p.start()
p.join()
我收到的输出如下:
main line
module name: __main__
parent process: 10812
process id: 11348*
现在很明显,控制台似乎只打印 info 函数,而不是 f 函数(使用 multiprocessing.Process)的任何输出。我在网上找到的其他示例也遇到过类似的问题:使用多处理时计算已完成并正确返回,但控制台中从未出现打印。
有人知道为什么以及如何解决这个问题吗?
在可能相关的说明中,我在 Spyder 3.2.4 中使用 Python 3.6。 Spyder 似乎有一些怪癖,因为代码中的第一行已经是允许多处理工作所需的解决方法,我发现这个问题已经讨论过here。提到了一个类似的未解决问题here。
感谢任何帮助,祝大家新年快乐。
【问题讨论】:
-
在 linux 上它确实打印出
f中的内容。你在哪个操作系统上? -
哦,你如何启动脚本? spyder我不知道,但是可能你直接在命令行调用脚本会得到不同的结果?
-
多处理在 Spyder 的 Windows 上不能正常工作,抱歉。您可以在外部终端中运行代码以获得所需的结果。为此,请转至
Run > Configuration per file > Execute in an external system terminal。 -
解决方案解释here:Spyder 似乎重定向stdout,在linux 上,一个分叉的进程从父进程继承stdout,在windows 中似乎不是这样,输出是在“默认标准输出”上完成,因此不会进入 spyder 控制台
-
非常感谢! hansaplast 的链接似乎解释了问题的根源,而 Carlos Cordoba 的建议显示了一种潜在的解决方法。
标签: python-3.x multiprocessing spyder