문제
그것은 선언을 더 이상 하나의 변수를 사용하여 with
문 Python?
다음과 같습니다.
from __future__ import with_statement
with open("out.txt","wt"), open("in.txt") as file_out, file_in:
for line in file_in:
file_out.write(line)
...또한 청소까지 두 가지 자원을 동시에 문제가?
해결책
가능합니다 v3.1 이후 Python 3 그리고 파이썬 2.7. 새로운 with
통사론 여러 상황 관리자를 지원합니다.
with A() as a, B() as b, C() as c:
doSomething(a,b,c)
와는 달리 contextlib.nested
, 이것은 그것을 보장합니다 a
그리고 b
그들의 가질 것입니다 __exit__()
'도라도 C()
아니면 그건 __enter__()
방법은 예외를 제기합니다.
다른 팁
contextlib.nested
이것을 지원합니다 :
import contextlib
with contextlib.nested(open("out.txt","wt"), open("in.txt")) as (file_out, file_in):
...
업데이트:
문서에 관한 문서를 인용합니다 contextlib.nested
:
버전 2.7 이후 더 이상 사용되지 않았습니다: With-Statement는 이제이 기능을 직접 지원합니다 (혼란스러운 오류가 발생하지 않으면 서).
보다 Rafał Dowgird의 대답 자세한 내용은.
변수를 라인으로 분할하면 Backslashes를 사용하여 Newlines를 감싸야합니다.
with A() as a, \
B() as b, \
C() as c:
doSomething(a,b,c)
파이썬은 대신 튜플을 생성하기 때문에 괄호는 작동하지 않습니다.
with (A(),
B(),
C()):
doSomething(a,b,c)
튜플이 부족하기 때문에 __enter__
속성, 오류가 발생합니다 (설명이없고 클래스 유형을 식별하지 않음) :
AttributeError: __enter__
당신이 사용하려고한다면 as
괄호 안에서 파이썬은 구문 분석 시간에 실수를 잡습니다.
with (A() as a,
B() as b,
C() as c):
doSomething(a,b,c)
SyntaxError : 유효하지 않은 구문
https://bugs.python.org/issue12782 이 문제와 관련된 것 같습니다.
대신 이것을하고 싶다고 생각합니다.
from __future__ import with_statement
with open("out.txt","wt") as file_out:
with open("in.txt") as file_in:
for line in file_in:
file_out.write(line)
이후 파이썬 3.3 사용할 수 있습니스 클래스 ExitStack
서 contextlib
모듈입니다.
그것을 관리 할 수 있습니다 동 숫자의 상황을 인식하는 개체는다는 것을 의미 증명하는 경우에 특히 유용하지 않는 방법을 알고 많은 파일을 처리합니다.
정식으로 사용하는 사례는 설명서에서 언급한 관리적의 파일이 있습니다.
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
여기에 일반적인 예제:
from contextlib import ExitStack
class X:
num = 1
def __init__(self):
self.num = X.num
X.num += 1
def __repr__(self):
cls = type(self)
return '{cls.__name__}{self.num}'.format(cls=cls, self=self)
def __enter__(self):
print('enter {!r}'.format(self))
return self.num
def __exit__(self, exc_type, exc_value, traceback):
print('exit {!r}'.format(self))
return True
xs = [X() for _ in range(3)]
with ExitStack() as stack:
print(stack._exit_callbacks)
nums = [stack.enter_context(x) for x in xs]
print(stack._exit_callbacks)
print(stack._exit_callbacks)
print(nums)
출력:
deque([])
enter X1
enter X2
enter X3
deque([<function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f86158>, <function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f861e0>, <function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f86268>])
exit X3
exit X2
exit X1
deque([])
[1, 2, 3]