如果我在Python 2.7.8中在IDLE中运行这个简单的代码,它会弹出一个窗口,说“该程序仍然在运行!你想杀死它吗?”。
from multiprocessing import Pool
def foo(x):
return x**2
if __name__ == '__main__':
pool = Pool(2)
pows = pool.map(foo, range(10))
print pows
即使我确实杀了(它会问两次)也不会发生任何事情。我曾经使用Windows,而我最近刚开始使用Mac OSX(10.9.4),我不知道我是否在这里遗漏了一些东西。
如果我直接在终端的Python Shell中运行相同的代码,它将运行良好。在iPython笔记本中也是如此。它只是不会在IDLE上弹出那个消息框。
有什么想法吗?我想继续使用IDLE ......
这是日志:
INFO:root:10221: Started process
INFO:root:10221: Defined foo
INFO:root:10221: __name__ == '__main__'
INFO:root:10221: pool created
答案 0 :(得分:1)
参考: https://docs.python.org/2/library/multiprocessing.html#introduction
具体来说,在注释中:
此程序包中的功能要求
__main__
模块 可由儿童进口。编程指南中对此进行了介绍 但是值得指出这里。这意味着一些例子, 例如multiprocessing.Pool
示例将不起作用 互动翻译。“
这是一个类似的问题Child processes created with python multiprocessing module won't print
将活动记录到文件的示例:
#!/usr/bin/env python
import logging
from multiprocessing import Pool
import os
logging.basicConfig(filename='example.log',level=logging.DEBUG)
def log_msg(msg):
logging.info("{}: {}".format(os.getpid(), msg))
log_msg("Started process")
def foo(x):
log_msg("running foo")
return x**2
log_msg("Defined foo")
if __name__ == '__main__':
log_msg("__name__ == '__main__'")
pool = Pool(2)
log_msg("pool created")
pows = pool.map(foo, range(10))
log_msg("map completed")
print pows
log_msg("output printed")
log_msg("Finished running")
我的输出示例:
tom@fannybawz:~$ ./multiproc.py
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
tom@fannybawz:~$ cat example.log
INFO:root:22238: Started process
INFO:root:22238: Defined foo
INFO:root:22238: __name__ == '__main__'
INFO:root:22238: pool created
INFO:root:22240: {}: running foo
INFO:root:22239: {}: running foo
INFO:root:22240: {}: running foo
INFO:root:22239: {}: running foo
INFO:root:22240: {}: running foo
INFO:root:22239: {}: running foo
INFO:root:22240: {}: running foo
INFO:root:22239: {}: running foo
INFO:root:22240: {}: running foo
INFO:root:22240: {}: running foo
INFO:root:22238: map completed
INFO:root:22238: output printed
INFO:root:22238: Finished running
tom@fannybawz:~$
使用Process版本自己尝试相同的事情。