我需要在 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__"
是绝对必要的。
通过在名称保护
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()''')