Python 多处理不断地产生 pythonw.exe 进程而不做任何实际工作 [英] Python multiprocessing continuously spawns pythonw.exe processes without doing any actual work

查看:31
本文介绍了Python 多处理不断地产生 pythonw.exe 进程而不做任何实际工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

# 文件:mp.py从多处理导入过程导入系统定义函数(x):打印作品",x + 2sys.stdout.flush()p = 进程(目标 = func, args = (2, ))p.start()p.join()p.terminate()打印完成"sys.stdout.flush()

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

python mp.py

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

解决方案

您需要保护然后使用 if __name__ == '__main__':.

进入程序的入口点

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

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

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

from multiprocessing import Process导入系统定义函数(x):打印作品",x + 2sys.stdout.flush()如果 __name__ == '__main__':p = 进程(目标 = func, args = (2, ))p.start()p.join()p.terminate()打印完成"sys.stdout.flush()

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:

python mp.py

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

解决方案

You need to protect then entry point of the program by using 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.exe processes as far as the eye can see.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆