多处理错误“AttributeError:无法在<模块'__main__"上获取属性'testfuncxx' [英] multiprocessing error "AttributeError: Can't get attribute 'testfuncxx' on <module '__main__"

查看:61
本文介绍了多处理错误“AttributeError:无法在<模块'__main__"上获取属性'testfuncxx'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/usr/bin/env python3.5
import multiprocessing, time

def testfuncxx(num):
    time.sleep(num)
    print(num


pool = multiprocessing.Pool(processes=3)

)

for i in range(10):
    #testfuncxx(i)
    #print(i, '=======')
    pool.apply_async(testfuncxx, args=(i,))

pool.close()
pool.join()

推荐答案

由于我只能在 Windows 上进行测试,因此当我将代码包含在 if __name__ == '__main__' 条目中时,该代码有效-点保护.更多详情此处.通常,建议在多处理指南中包含此保护.

Since I can only test on Windows, the code works when I enclose the code in a if __name__ == '__main__' entry-point protection. More details here. In general, including this protection is recommended in the multiprocessing guidelines.

注意:代码作为脚本test.py运行.要在 IPython 或 Jupyter notebook 中运行代码,您可以像 import test 一样导入它.

Note: The code was run as a script test.py. To run the code in IPython or Jupyter notebook, you may import it like import test.

test.py:

import multiprocessing, time

def testfuncxx(num):
    time.sleep(num)    
    print(num)

def apply_async_callback():  
    pool = multiprocessing.Pool(processes=3) 
    for i in range(10):  
        pool.apply_async(testfuncxx, args=(i,))
    pool.close()
    pool.join()  


if __name__=='__main__':    
    apply_async_callback()

#Output:
0
1
2
3
4
5
6
7
8
9

这篇关于多处理错误“AttributeError:无法在<模块'__main__"上获取属性'testfuncxx'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆