這個怎麼樣?
class ListContext:
def __init__(self, l):
self.l = l
def __enter__(self):
for x in self.l:
x.__enter__()
return self.l
def __exit__(self, type, value, traceback):
for x in self.l:
x.__exit__(type, value, traceback)
arr = ['a', 'b', 'c']
with ListContext([open(fn, 'w') for fn in arr]) as files:
print files
print files
輸出是:
[<open file 'a', mode 'w' at 0x7f43d655e390>, <open file 'b', mode 'w' at 0x7f43d655e420>, <open file 'c', mode 'w' at 0x7f43d655e4b0>]
[<closed file 'a', mode 'w' at 0x7f43d655e390>, <closed file 'b', mode 'w' at 0x7f43d655e420>, <closed file 'c', mode 'w' at 0x7f43d655e4b0>]
通告,它們與上下文內的打開和關閉外部。
這是使用Python的context manager API。
編輯:它似乎已經存在,但是已棄用:請參閱contextlib和this SO question。使用這樣的:
import contextlib
with contextlib.nested(*[open(fn, 'w') for fn in arr]) as files:
print files
print files
來源
2013-10-16 19:53:01
Max
您可以編寫自己的上下文管理器。這是一個選擇嗎?這很容易。 http://docs.python.org/release/2.5.1/ref/context-managers.html –