Python의 다중 처리에서 "AttributeError : __exit__"문제를 해결하는 방법은 무엇입니까?


87

Python 3.2.2의 여러 코어에서 실행할 수 있도록 일부 csv 읽기 코드를 다시 작성하려고했습니다. 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)

이 문제를 해결하는 좋은 방법은 무엇입니까?


1
제 경우에는 None범위 지정 문제로 인해 실수로 통과했습니다 .
— ThorSummoner

클래스를 선언 할 때 클래스에서 Class SomeClass(object):명시 적으로 이탈 이있는 것처럼이 문제가 발생했습니다 . 상속을 제거하면 object작동했습니다. 나도 몰라, 왜 YMMV 그래서
— mpag

답변:


154

문제는 다음 줄에 있습니다.

with pattern.findall(row) as f:

당신은 with진술을 사용하고 있습니다. __enter__및 __exit__메서드 가있는 개체가 필요합니다 . 그러나 pattern.findall반환 a는 list, with가게하려고 __exit__방법을하지만, 그것을 찾을 수 없습니다, 및 오류를 발생시킵니다. 그냥 사용

f = pattern.findall(row)

대신.


62

이 경우 요청자의 문제는 아니지만 일반적인 "AttributeError : __exit__"에 대한 첫 번째 문제 해결 단계는 대괄호가 있는지 확인하는 것입니다.

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

아니

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

가끔 나를 잡아 내고 여기서 끝납니다 -__-


9

오류는 사용하려고 할 때도 발생합니다.

with multiprocessing.Pool() as pool:
   # ...

Python 2.X와 같이 너무 오래 with되어 다중 처리 풀과 함께 사용 하는 것을 지원하지 않는 Python 버전 .

(자세한 내용 은 다른 질문에 대한 답변 https://stackoverflow.com/a/25968716/1426569 참조)


네! Python 3.X에서 훌륭하게 작업
— Sreekant Shenoy

-1

이 오류의 원인은 다음과 같습니다. Flask 앱이 이미 실행 중이고 종료되지 않았으며 그 중간에 다음과 같은 방법으로 다른 인스턴스를 시작하려고합니다. with app.app_context () : #Code이 with 문을 사용하기 전에 만들어야합니다. 이전에 실행중인 앱의 범위가 닫혀 있는지 확인하십시오.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.