Python 多处理在 linux 中有效,但在 windows 中无效

标签 python linux windows multiprocessing

我有一个多处理脚本,我在 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/

相关文章:

java - 如何修复在给出 "SocketException: Permission denied: connect"的命令行窗口中使用的 jarsigner 问题

Python - 我应该将我的辅助函数放在类内还是类外?

python - 人为限制时索引超出范围

java - 通过 JNA 使用 Xlib 移动窗口

linux - 是否有适用于企业的颠覆设备/工具集

Windows 32位虚拟内存页面映射问题

C# 存储数字的安全方式?

python - 在python中将多个Excel文件(xlsx)附加在一起

python - Pandas 列多索引到行多索引

java - 如何向现有的 bash 进程发出多个命令?