在Python中结合with语句和for循环

问题描述 投票:0回答:1

考虑以下使用上下文管理器获取和释放资源的python代码:

from contextlib import contextmanager

@contextmanager
def res(i):
    print(f'Opening resource {i}')
    yield
    print(f'Closing resource {i}')

现在假设我们需要使用其中一些资源

with res(0), res(1), res(2):
    print('Using resources.')

其中内部部分取决于同时打开所有三个资源。运行上面的代码后,我们得到预期的输出:

Opening resource 0
Opening resource 1
Opening resource 2
Using resources.
Closing resource 2
Closing resource 1
Closing resource 0

如果您必须使用更多资源-res(0) ... res(10)是否可以使用for循环动态生成与下面的伪代码等效的代码?

with res(0), res(1), ... , res(10):
    print('Using resources.')
python for-loop with-statement contextmanager
1个回答
0
投票
这是contextlib.ExitStack的作用。

with ExitStack() as es: for x in range(10): es.enter_context(res(x))

with语句完成后,堆栈中的每个上下文管理器将以与输入时相反的顺序退出。
© www.soinside.com 2019 - 2024. All rights reserved.