gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:12:18 25 4
gpt4 key购买 nike

考虑以下使用上下文管理器获取和释放资源的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com