在 python 中组合 with 语句和 for 循环

Combining a with statement and a for loop in python

考虑以下 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.')

这就是 contextlib.ExitStack 的用途。

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

一旦 with 语句完成,堆栈中的每个上下文管理器将按照它们进入的相反顺序退出。