Python multiprocessing continuously spawns pythonw.exe processes without doing any actual work(Python 多处理不断产生 pythonw.exe 进程而不做任何实际工作)
问题描述
我不明白为什么这么简单的代码
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
我在 32 位和 64 位的 Windows 7 上运行最新的 Python 2.6
I am running the latest of Python 2.6 on Windows 7 both 32 and 64 bits
推荐答案
你需要保护然后使用 if __name__ == '__main__': 进入程序的入口点.
You need to protect then entry point of the program by using 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 进程而不做任何实际工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 多处理不断产生 pythonw.exe 进程而不做任何实际工作
基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
