python - 在 python 中结合 with 语句和 for 循环

标签 python loops for-loop with-statement contextmanager

考虑以下使用上下文管理器获取和释放资源的 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 语句完成,堆栈中的每个上下文管理器将按照它们进入的相反顺序退出。

关于python - 在 python 中结合 with 语句和 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58567795/

相关文章:

javascript - Vue 警告无限循环,除非我创建对象的副本

arrays - Go 中的嵌套循环数组的行为不像其他语言的数组

java - 带循环的正整数对

python - 如果我不尝试迭代,为什么我会得到 "type ' bool' is not iterable"?

python - 使用正则表达式过滤列表

c - 实验室代码逻辑错误,C程序初学者

javascript - 如何在 javascript/jquery 循环中的 x 项之后包装元素?

python - 用python从不规则值中提取数字

python - 需要关闭 python 套接字/在我的开发环境中查找当前正在运行的服务器

swift - For循环等待和延迟 - Swift 4