首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在“with”语句中有多个变量?

在“with”语句中有多个变量?
EN

Stack Overflow用户
提问于 2009-05-21 22:51:27
回答 4查看 157.3K关注 0票数 499

是否可以在Python语言中使用with语句声明多个变量?

类似于:

from __future__ import with_statement

with open("out.txt","wt"), open("in.txt") as file_out, file_in:
    for line in file_in:
        file_out.write(line)

..。或者同时清理两个资源就是问题所在?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-07-02 11:25:51

这在Python 3 since v3.1Python 2.7中是可能的。新的with syntax支持多个上下文管理器:

with A() as a, B() as b, C() as c:
    doSomething(a,b,c)

contextlib.nested不同的是,这保证了ab将调用它们的__exit__(),即使C()或它的__enter__()方法引发异常。

您还可以在以后的定义中使用较早的变量(下面的h/t Ahmad ):

with A() as a, B(a) as b, C(a, b) as c:
    doSomething(a, c)

从Python3.10开始,you can use parentheses

with (
    A() as a, 
    B(a) as b, 
    C(a, b) as c,
):
    doSomething(a, c)
票数 823
EN

Stack Overflow用户

发布于 2009-05-21 14:55:23

我认为你应该这样做:

from __future__ import with_statement

with open("out.txt","wt") as file_out:
    with open("in.txt") as file_in:
        for line in file_in:
            file_out.write(line)
票数 17
EN

Stack Overflow用户

发布于 2021-02-26 23:37:46

从Python3.10开始,Parenthesized context managers有了一个新特性,它支持如下语法:

with (
    A() as a,
    B() as b
):
    do_something(a, b)
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/893333

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档