問(wèn)題描述
我不明白為什么這么簡(jiǎn)單的代碼
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()
連續(xù)創(chuàng)建pythonw.exe"進(jìn)程并且它不打印任何東西,即使我從命令行運(yùn)行它:
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 上運(yùn)行最新的 Python 2.6
I am running the latest of Python 2.6 on Windows 7 both 32 and 64 bits
推薦答案
你需要保護(hù)然后使用 if __name__ == '__main__':
進(jìn)入程序的入口點(diǎn).
You need to protect then entry point of the program by using if __name__ == '__main__':
.
這是一個(gè)特定于 Windows 的問(wèn)題.在 Windows 上,您的模塊必須導(dǎo)入新的 Python 解釋器才能訪問(wèn)您的目標(biāo)代碼.如果你不停止這個(gè)新的解釋器運(yùn)行啟動(dòng)代碼,它將產(chǎn)生另一個(gè)孩子,然后再產(chǎn)生另一個(gè)孩子,直到它的 pythonw.exe
進(jìn)程一目了然.
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.
其他平臺(tái)使用os.fork()
啟動(dòng)子進(jìn)程,所以不存在重新導(dǎo)入模塊的問(wèn)題.
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()
這篇關(guān)于Python 多處理不斷產(chǎn)生 pythonw.exe 進(jìn)程而不做任何實(shí)際工作的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!