简体   繁体   English

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

[英]Combining a with statement and a for loop in python

Consider the following python code which uses a context manager to acquire and release a resource:考虑以下 python 代码,它使用上下文管理器来获取和释放资源:

from contextlib import contextmanager

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

Now assume that we need to use a couple of those resources现在假设我们需要使用其中的一些资源

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

where the inner part depends on all the three resources being open simultaneously.其中内部取决于同时打开的所有三个资源。 After running the code above, we get the expected output:运行上面的代码后,我们得到了预期的 output:

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

If you have to use even more resources - res(0)... res(10) is it possible to dynamically generate using a for loop the equivalent of the pseudo code below?如果您必须使用更多资源 - res(0)... res(10)是否可以使用与下面的伪代码等效的 for 循环动态生成?

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

This is what contextlib.ExitStack is for.这就是contextlib.ExitStack的用途。

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

Each context manager in the stack will be exited in the reverse order they were entered, once the with statement completes.一旦with语句完成,堆栈中的每个上下文管理器都将以它们进入的相反顺序退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM