windows Python 多处理不断地产生 pythonw.exe 进程而不做任何实际工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3405397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:58:17  来源:igfitidea点击:

Python multiprocessing continuously spawns pythonw.exe processes without doing any actual work

pythonwindowsprocessmultiprocessing

提问by lj8888

I don't understand why this simple code

我不明白为什么这个简单的代码

# file: mp.py
from multiprocessing import Process
import sys

def func(x):
    print 'works ', x + 2
    sys.stdout.flush()

p = Process(target= func, args= (2, ))
p.start()
p.join()
p.terminate()
print 'done'
sys.stdout.flush()

creates "pythonw.exe" processes continuously and it doesn't print anything, even though I run it from the command line:

连续创建“pythonw.exe”进程并且它不打印任何内容,即使我从命令行运行它:

python mp.py

I am running the latest of Python 2.6 on Windows 7 both 32 and 64 bits

我在 32 位和 64 位的 Windows 7 上运行最新的 Python 2.6

回答by Dave Webb

You need to protect then entry point of the program by using if __name__ == '__main__':.

您需要使用if __name__ == '__main__':.

This is a Windows specific problem. On Windows your module has to be imported into a new Python interpreter in order for it to access your target code. If you don't stop this new interpreter running the start up code it will spawn another child, which will then spawn another child, until it's pythonw.exeprocesses as far as the eye can see.

这是 Windows 特定的问题。在 Windows 上,您的模块必须导入到新的 Python 解释器中才能访问您的目标代码。如果你不停止这个新的解释器运行启动代码,它会产生另一个孩子,然后又会产生另一个孩子,直到它的pythonw.exe进程就在眼前。

Other platforms use os.fork()to launch the subprocesses so don't have the problem of reimporting the module.

其他平台用于os.fork()启动子进程,因此没有重新导入模块的问题。

So your code will need to look like this:

因此,您的代码需要如下所示:

from multiprocessing import Process
import sys

def func(x):
    print 'works ', x + 2
    sys.stdout.flush()

if __name__ == '__main__':
    p = Process(target= func, args= (2, ))
    p.start()
    p.join()
    p.terminate()
    print 'done'
    sys.stdout.flush()

回答by macedoine

According to the programming guidelinesfor multiprocessing, on windows you need to use an if __name__ == '__main__':

根据multiprocessing的编程指南,在 Windows 上,您需要使用if __name__ == '__main__':

回答by sarnold

Funny, works on my Linux machine:

有趣,适用于我的 Linux 机器:

$ python mp.py
works  4
done
$

Is the multiprocessing thing supposed to work on Windows? A lot of programs originated in the Unix world don't handle Windows so well, because Unix uses fork(2)to clone processes quite cheaply, but (it is my understanding) that Windows does not support fork(2)gracefully, if at all.

多处理的东西应该在 Windows 上工作吗?许多起源于 Unix 世界的程序不能很好地处理 Windows,因为 Unixfork(2)用来克隆进程的成本非常低,但是(我的理解)Windows 根本不支持fork(2),如果有的话。