无法在Python中的exec函数中使用多重处理

问题描述 投票:0回答:1

我需要在 exec 函数内使用多重处理,但出现错误。

if __name__ == "__main__":
    exec('''from multiprocessing import Pool
def func():
    print(1)
if __name__ == "__main__":
    with Pool(4) as pool:
        pool.apply_async(func)
        pool.close()
        pool.join()''')

执行时出现如下错误。

AttributeError: Can't get attribute 'func' on <module '__mp_main__' from 'filename'>

上面是有问题的代码,如果我删除顶部的
if __name__ == "__main__"
,它就可以正常工作。
但这
if __name__ == "__main__"
是绝对必要的。

python-3.x multiprocessing exec
1个回答
0
投票

通过在名称保护

func
中定义函数
if __name__ == "__main__":
,子进程(其
__name__
'__mp_main__'
)不会执行
def func()
语句来在其命名空间中定义该函数,因此
AttributeError

您应该在名称保护之外定义子进程需要的对象:

def func():
    print(1)

exec('''from multiprocessing import Pool

if __name__ == "__main__":
    with Pool(4) as pool:
        pool.apply_async(func)
        pool.close()
        pool.join()''')
© www.soinside.com 2019 - 2024. All rights reserved.