【问题标题】:Python multiprocessing works in linux but not in windowsPython 多处理在 linux 中有效,但在 windows 中无效
【发布时间】:2016-03-17 11:52:35
【问题描述】:

我有一个多处理脚本,我在 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 一样的确切结果,并且脚本甚至没有结束(但是如果我删除了多处理,脚本可以工作)

我应该如何解决才能使多处理工作?

【问题讨论】:

  • 你应该在maping 之后在池上调用.close().terminate(),以确保工人在完成工作后会结束,但 falsetru 的回答是主要问题。

标签: python linux windows multiprocessing


【解决方案1】:

根据multiprocessing documentation - Programming guidelines - Windows

主模块的安全导入

确保新的 Python 解释器可以安全地导入主模块,而不会导致意外的副作用(例如启动新进程)。

...

相反,应该通过使用来保护程序的“入口点” if __name__ == '__main__':如下:

...

所以,用 if __name__ == '__main__' 保护 get_urls1() 调用:

if __name__ == '__main__':
    get_urls1()

【讨论】:

    猜你喜欢
    • 2015-07-16
    • 2014-10-23
    • 2020-04-14
    • 2017-05-13
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多