使用Python“with”statemens时捕获异常

2024-04-20 07:02:38 发布

您现在位置:Python中文网/ 问答频道 /正文

遗憾的是,我不知道如何处理python“with”语句的异常。如果我有密码:

with open("a.txt") as f:
    print f.readlines()

我真的想处理'文件找不到异常',以便做一些事情。但我不会写

with open("a.txt") as f:
    print f.readlines()
except:
    print 'oops'

不会写字

with open("a.txt") as f:
    print f.readlines()
else:
    print 'oops'

在try/except语句中包含“with”不起作用,否则:不会引发异常。我该怎么做才能用Pythonic的方式处理“with”语句中的失败?


Tags: 文件txt密码aswith语句open事情
3条回答

Catching an exception while using a Python 'with' statement

with语句在没有__future__导入since Python 2.6的情况下可用。您可以将其命名为early as Python 2.5(但现在是升级的时候了!)使用:

from __future__ import with_statement

这是你最接近的纠正方法。你就快到了,但是with没有except子句:

with open("a.txt") as f: 
    print(f.readlines())
except:                    # <- with doesn't have an except clause.
    print('oops')

上下文管理器的__exit__方法,如果返回False,则在完成时将重新引发错误。如果它返回True,它将抑制它。内置的open不返回True,所以您只需要尝试嵌套它,除了块:

try:
    with open("a.txt") as f:
        print(f.readlines())
except Exception as error: 
    print('oops')

标准样板文件:不要使用捕获BaseException和其他所有可能的异常和警告的裸except:。至少和Exception一样具体,对于这个错误,可能会捕获IOError。只捕获准备好处理的错误。

在这种情况下,你应该:

>>> try:
...     with open("a.txt") as f:
...         print(f.readlines())
... except IOError as error: 
...     print('oops')
... 
oops
from __future__ import with_statement

try:
    with open( "a.txt" ) as f :
        print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
    print 'oops'

如果您希望对开放调用和工作代码中的错误进行不同的处理,可以执行以下操作:

try:
    f = open('foo.txt')
except IOError:
    print('error')
else:
    with f:
        print f.readlines()

利用with语句,最好的“Pythonic”方法列为PEP 343中的示例6,它给出了语句的背景。

@contextmanager
def opened_w_error(filename, mode="r"):
    try:
        f = open(filename, mode)
    except IOError, err:
        yield None, err
    else:
        try:
            yield f, None
        finally:
            f.close()

使用如下:

with opened_w_error("/etc/passwd", "a") as (f, err):
    if err:
        print "IOError:", err
    else:
        f.write("guido::0:0::/:/bin/sh\n")

相关问题 更多 >