【问题标题】:Run a multiprocessing job with Python 2.7 / Windows使用 Python 2.7 / Windows 运行多处理作业
【发布时间】:2018-02-02 11:11:28
【问题描述】:

基于this answer,我想用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:\Users\User\Desktop\test.py”,第 14 行,在 main res = pool.map(jobWrapper, the_args) 文件“C:\Python27\lib\multiprocessing\pool.py”,第 251 行,在地图中 return self.map_async(func, iterable, chunksize).get() 文件“C:\Python27\lib\multiprocessing\pool.py”,第 558 行,在 get 提高自我价值 cPickle.PicklingError: Can't pickle : attribute lookup >builtin.function failed

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

【问题讨论】:

标签: python windows multiprocessing python-multiprocessing


【解决方案1】:

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

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()

您还需要在 windows 中调用freeze_support

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2017-11-03
    • 2011-07-23
    • 1970-01-01
    • 2013-10-08
    • 2017-11-15
    • 1970-01-01
    相关资源
    最近更新 更多