使用 Python 2.7 引发属性错误的多处理
Posted
技术标签:
【中文标题】使用 Python 2.7 引发属性错误的多处理【英文标题】:Multiprocessing with Python 2.7 throwing attribute error 【发布时间】:2021-10-19 05:16:37 【问题描述】:from itertools import product
from multiprocessing import Pool
with Pool(4) as pool:
pool.map(lambda x: run_test_function(x, arg2, arg3, arg4), arg1)
执行上述代码后出现以下错误。还有一些其他的代码,我不能在这里写。但实际问题仅来自这段代码。
Traceback (most recent call last):
File "modProfileChange_test.py", line 347, in <module>
main(sys.argv[1:])
File "modProfileChange_test.py", line 336, in main
test_run_code(arg1, arg2, arg3, arg4, arg5, arg6)
File "modProfileChange_test.py", line 23, in test_run_code
with Pool(4) as pool:
AttributeError: __exit__
【问题讨论】:
这已经是语法上有效的 Python 2.7 代码 那么使用的库呢?我只在另一个问题上关注您的代码。所以我对这个库不太熟悉。 没什么特别的,我猜?这是有效的 Python 2.7 代码 它的抛出错误。 您发布的代码只有 5 行。请发布minimal reproducible example 和full 错误消息(应以“Traceback”一词开头)。 【参考方案1】:-
在 Python 2.7 中,
multiprocessing.Pool
不是上下文管理器,因此不能在 with
语句中使用
-
解决方案 - 使用对变量的常规分配创建池:
my_pool = Pool(4)
my_pool.map(...)
lambda
functions don't work with multiprocessing.Pool
,即使在 Python 3 中也是如此。
-
解决方案 - 使用上面链接中的解决方案模拟闭包:
from functors import partial
def run_test_function(x, fun_arg2, fun_arg3, fun_arg4):
# your code here
...
process_func = partial(run_test_function, fun_arg2=arg2, fun_arg3=arg3, fun_arg4=arg4)
把这些放在一起:
from multiprocessing import Pool
from functools import partial
def run_test_function(x, fun_arg2, fun_arg3, fun_arg4):
# this is an example
print x, fun_arg2, fun_arg3, fun_arg4
if __name__ == "__main__":
arg1 = 1,2,3,4
arg2 = "hello"
arg3 = "world"
arg4 = "!"
process_func = partial(run_test_function, fun_arg2=arg2, fun_arg3=arg3, fun_arg4=arg4)
my_pool = Pool(4)
my_pool.map(process_func, arg1)
输出:
~/test $ python2.7 so10.py
1 hello world !
2 hello world !
3 hello world !
4 hello world !
【讨论】:
谢谢,它对我有用。我们可以提供的处理器范围是多少?正如你给出的 4,这个值取决于什么因素? 如果您的工作负载是 CPU 密集型的(这是multiprocessing
模块的用途,而不是 threading
模块),每个 CPU 内核创建一个进程是有意义的。我知道我的 CPU 有 4 个内核,所以我创建了 4 个进程。 Pool
can determine the number of cores automatically,所以你可以直接使用Pool()
,不带任何参数
脚本执行后,脚本运行正常,但 cli 挂起,无响应。
@Vanshika,脚本是什么?我的答案中的那个?
是的,这只是我在脚本中使用的示例。此外,输出没有格式化,就像你得到 1 hello world !,但它应该像 1 \nhello \nworld \n!以上是关于使用 Python 2.7 引发属性错误的多处理的主要内容,如果未能解决你的问题,请参考以下文章
Google App Engine 上的错误 Python 2.7 - 无法使用 CGI 处理程序启用线程安全
Python 2.7 urllib2 在使用 xml 内容点击重定向时引发 urllib2.HTTPError 301
即使一切都是 unicode(python 2.7),ascii 解码错误