使用 Python 2.7 / Windows 运行多处理作业



基于这个答案,我想用Python 2.7/Windows运行这个multiprocessing作业:

def main():
    import itertools as it
    from multiprocessing import Pool
    def dothejob(i, j, k):
        print i, j, k
    the_args = it.product(range(100), range(100), range(100))
    pool = Pool(4)
    def jobWrapper(args): 
        return dothejob(*args)
    res = pool.map(jobWrapper, the_args)
if __name__ == '__main__':
    main()    

main()和最后两行是必需的,因为没有它们,就会有一个众所周知的错误:

这可能意味着你在Windows上,你有 忘记在主模块中使用正确的习语:

if __name__ == '__main__':
    ....

但即使这样,我也会收到此错误:

文件"C:\用户\用户\桌面\test.py",第 14 行,在主 res = pool.map(jobWrapper, the_args( 文件 "C:\Python27\lib\multiprocessing\pool.py",第 251 行,在映射中 返回self.map_async(func, iterable, chunksize(.get(( 文件 "C:\Python27\lib\multiprocessing\pool.py",第 558 行,在 get 提高self._value cPickle.PicklingError: Can't pickle : 属性查找>builtin.function 失败

这里涉及cPickle在哪里,为什么会出现此错误/如何解决?

所有定义都必须在模块范围内:

import itertools as it
from multiprocessing import Pool, freeze_support
def dothejob(i, j, k):
    print i, j, k
def jobWrapper(args): 
    return dothejob(*args)
def main():
    the_args = it.product(range(100), range(100), range(100))
    pool = Pool(4)
    res = pool.map(jobWrapper, the_args)
if __name__ == '__main__':
    freeze_support() #you need this in windows
    main()

您还需要在窗口中调用freeze_support

相关内容

  • 没有找到相关文章

最新更新