如何在Python中的多进程中解决“AttributeError:__ exit__”问题?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在Python中的多进程中解决“AttributeError:__ exit__”问题?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2169字,纯文字阅读大概需要4分钟。
内容图文
![如何在Python中的多进程中解决“AttributeError:__ exit__”问题?](/upload/InfoBanner/zyjiaocheng/951/03b69d31fd2041a18ae61ca05928f134.jpg)
我试图重写一些csv读取代码,以便能够在Python 3.2.2中的多个核心上运行它.我尝试使用多处理的Pool对象,我从工作示例改编(并且已经为我的项目的另一部分工作).我遇到了一条错误消息,我发现很难解密和排除故障.
错误:
Traceback (most recent call last):
File "parser5_nodots_parallel.py", line 256, in <module>
MG,ppl = csv2graph(r)
File "parser5_nodots_parallel.py", line 245, in csv2graph
node_chunks)
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/multiprocessing/pool.py", line 552, in get
raise self._value
AttributeError: __exit__
相关代码:
import csv
import time
import datetime
import re
from operator import itemgetter
from multiprocessing import Pool
import itertools
def chunks(l,n):
"""Divide a list of nodes `l` in `n` chunks"""
l_c = iter(l)
while 1:
x = tuple(itertools.islice(l_c,n))
if not x:
return
yield x
def csv2nodes(r):
strptime = time.strptime
mktime = time.mktime
l = []
ppl = set()
pattern = re.compile(r"""[A-Za-z0-9"/]+?(?=[,\n])""")
for row in r:
with pattern.findall(row) as f:
cell = int(f[3])
id = int(f[2])
st = mktime(strptime(f[0],'%d/%m/%Y'))
ed = mktime(strptime(f[1],'%d/%m/%Y'))
# collect list
l.append([(id,cell,{1:st,2: ed})])
# collect separate sets
ppl.add(id)
return (l,ppl)
def csv2graph(source):
MG=nx.MultiGraph()
# Remember that I use integers for edge attributes, to save space! Dic above.
# start: 1
# end: 2
p = Pool()
node_divisor = len(p._pool)
node_chunks = list(chunks(source,int(len(source)/int(node_divisor))))
num_chunks = len(node_chunks)
pedgelists = p.map(csv2nodes,
node_chunks)
ll = []
ppl = set()
for l in pedgelists:
ll.append(l[0])
ppl.update(l[1])
MG.add_edges_from(ll)
return (MG,ppl)
with open('/Users/laszlosandor/Dropbox/peers_prisons/python/codetenus_test.txt','r') as source:
r = source.readlines()
MG,ppl = csv2graph(r)
解决这个问题的好方法是什么?
解决方法:
问题出在这一行:
with pattern.findall(row) as f:
您正在使用with语句.它需要一个带有__enter__和__exit__方法的对象.但是pattern.findall返回一个列表,尝试存储__exit__方法,但是找不到它,并引发错误.只是用
f = pattern.findall(row)
代替.
内容总结
以上是互联网集市为您收集整理的如何在Python中的多进程中解决“AttributeError:__ exit__”问题?全部内容,希望文章能够帮你解决如何在Python中的多进程中解决“AttributeError:__ exit__”问题?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。