Python多重处理不断产生pythonw.exe进程,而没有做任何实际工作 [英] Python multiprocessing continuously spawns pythonw.exe processes without doing any actual work
问题描述
我不明白为什么这样简单的代码
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()
连续创建"pythonw.exe"进程,即使我从命令行运行它也不会打印任何内容:
creates "pythonw.exe" processes continuously and it doesn't print anything, even though I run it from the command line:
python mp.py
我正在Windows 7(32位和64位)上运行最新的Python 2.6
I am running the latest of Python 2.6 on Windows 7 both 32 and 64 bits
推荐答案
您需要保护然后使用if __name__ == '__main__':
.
这是Windows特定的问题.在Windows上,必须将模块导入新的Python解释器中才能访问目标代码.如果不停止运行运行启动代码的新解释器,它将生成另一个子代,然后再生成另一个子代,直到它的pythonw.exe
进程为止.
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.exe
processes as far as the eye can see.
其他平台使用 os.fork()
启动子进程,所以不要没有重新导入模块的问题.
Other platforms use os.fork()
to launch the subprocesses so don't have the problem of reimporting the module.
因此您的代码将需要如下所示:
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()
这篇关于Python多重处理不断产生pythonw.exe进程,而没有做任何实际工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!