gpt4 book ai didi

Python 多处理库错误(AttributeError : __exit__)

转载 作者:IT老高 更新时间:2023-10-28 22:03:12 28 4
gpt4 key购买 nike

使用 pool.map(funct, iterable) 时出现此错误:

AttributeError: __exit__

没有解释,只是堆栈跟踪到模块内的 pool.py 文件。

这样使用:

with Pool(processes=2) as pool:
pool.map(myFunction, mylist)
pool.map(myfunction2, mylist2)

我怀疑picklability可能存在问题(python需要pickle,或将列表数据转换为字节流)但我不确定这是真的还是如何调试。

编辑:产生此错误的新代码格式:

def governingFunct(list):
#some tasks
def myFunction():
# function contents
with closing(Pool(processes=2)) as pool:
pool.map(myFunction, sublist)
pool.map(myFunction2, sublist2)

产生错误:

PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

最佳答案

在 Python 2.x 和 3.0、3.1 和 3.2 中,multiprocessing.Pool() 对象不是上下文管理器。您不能在 with 语句中使用它们。只有在 Python 3.3 及更高版本中,您才能使用它们。来自 Python 3 multiprocessing.Pool() documentation :

New in version 3.3: Pool objects now support the context management protocol – see Context Manager Types. __enter__() returns the pool object, and __exit__() calls terminate().

对于早期的 Python 版本,您可以使用 contextlib.closing() ,但考虑到这将调用 pool.close(),而不是 pool.terminate()。在这种情况下手动终止:

from contextlib import closing

with closing(Pool(processes=2)) as pool:
pool.map(myFunction, mylist)
pool.map(myfunction2, mylist2)
pool.terminate()

或创建自己的 terminating() 上下文管理器:

from contextlib import contextmanager

@contextmanager
def terminating(thing):
try:
yield thing
finally:
thing.terminate()

with terminating(Pool(processes=2)) as pool:
pool.map(myFunction, mylist)
pool.map(myfunction2, mylist2)

关于Python 多处理库错误(AttributeError : __exit__),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25968518/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com