题
是否有可能宣布的多个变量使用 with
发言蟒蛇?
是这样的:
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)
...或是清理了两种资源在同一时间问题吗?
其他提示
contextlib.nested
支持这样的:
import contextlib
with contextlib.nested(open("out.txt","wt"), open("in.txt")) as (file_out, file_in):
...
<强>更新强>结果
引用的文档,关于 contextlib.nested
:
在与语句现在支持这一点:自2.7版的弃用 功能直接(不混淆容易出错怪癖)。
有关详细信息,请参见拉法尔Dowgird的回答。
请注意,如果分割成变量线,则必须使用反斜杠来包装换行。
with A() as a, \
B() as b, \
C() as c:
doSomething(a,b,c)
括号不起作用,因为Python创建一个元组,而不是
with (A(),
B(),
C()):
doSomething(a,b,c)
由于元组缺乏__enter__
属性,则得到一个错误(undescriptive和不标识类型):
AttributeError: __enter__
如果您尝试括号内使用as
,巨蟒捕获错误在分析时:
with (A() as a,
B() as b,
C() as c):
doSomething(a,b,c)
语法错误:无效的语法
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)
因为Python 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]
不隶属于 StackOverflow