2011-09-16 5 views
61

파이썬 3.2.2에서 여러 코어에서 실행할 수 있도록 일부 csv- 읽기 코드를 다시 작성하려고했습니다. 나는 멀티 프로세싱의 Pool 객체를 사용하려고 시도했다. 나는이 예제를 작업 예제에서 수정했다. (이미 프로젝트의 다른 부분에서 나를 위해 일했다.) 해독 및 문제 해결에 열심 인 오류 메시지가 나타났습니다. 이 문제를 해결하는 좋은 방법은 무엇입니까? 감사!Python의 다중 처리에서 "AttributeError : __exit__"문제를 해결하는 방법은 무엇입니까?

오류 :

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) 
+1

, 내가 실수로 범위 지정으로 인해'None'를 통과했다하지 문제. – ThorSummoner

+0

내 클래스에 명시 적으로 __exit__을 가지고 있는데 클래스를 'Class SomeClass (object) :'로 선언 할 때이 코드를 사용했습니다. 일단 객체로부터 상속을 제거하면 효과가있었습니다. 나는 이유를 모른다. 그래서 YMMV – mpag

답변

111

문제는이 라인에 있습니다

with pattern.findall(row) as f: 

당신은 with 문을 사용하고 있습니다. __enter____exit__ 메서드가있는 객체가 필요합니다. 그러나 pattern.findalllist을 반환하고 with 메서드를 저장하려고 시도하지만 찾을 수 없으며 오류가 발생합니다. 그냥

f = pattern.findall(row) 

대신 사용하십시오.

39

이 인스턴스에서는 묻는 사람의 문제가 아니지만 첫 번째 일반 "AttributeError : __exit__"에 대한 문제 해결 단계에서 대괄호가 있는지 확인해야합니다.

with SomeEnterExitObject() as foo: 
    #works because a new object is referenced... 

with SomeEnterExitObject as foo: 
    #AttributeError because the class is referenced 

때때로 밖으로 잡아 나를 내가 여기까지 -__- 내 경우

관련 문제