我有一个多处理脚本,我在 linux 和 windows 上都试过了
在 linux 中它工作正常但在 windows 中脚本运行一些随机的未知结果并且脚本甚至没有结束
脚本
from multiprocessing.pool import Pool
def get_urls1():
res = [1,2,3,4,5]
nprocs = 20 # nprocs is the number of processes to run
ParsePool = Pool(nprocs)
#ParsePool.map(btl_test,url)
ParsedURLS = ParsePool.map(extractData,res)
def extractData(r):
print r
get_urls1()
Linux 输出
1
3
2
5
4
但是当我在 windows 中运行相同的脚本时,它没有给出准确的结果,因为 linux 并且脚本甚至没有结束(但是如果我删除 multiprocessing 脚本工作)
我应该修复什么才能使多处理正常工作?
最佳答案
根据 multiprocessing
documentation - Programming guidelines - Windows
Safe importing of main module
Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process).
...
Instead one should protect the “entry point” of the program by using
if __name__ == '__main__':
as follows:...
因此,守卫 get_urls1() 调用 if __name__ == '__main__'
:
if __name__ == '__main__':
get_urls1()
关于Python 多处理在 linux 中有效,但在 windows 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36059796/