首页 文章

使用Python 'with'语句时捕获异常

提问于
浏览
218

令我遗憾的是,我无法弄清楚如何处理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'语句中的失败,我该怎么办?

4 回答

  • 197
    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()
    
  • -2

    利用 with 语句执行此操作的最佳方法在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")
    
  • 45

    使用Python'with'语句时捕获异常

    with语句在没有 __future__ import since Python 2.6的情况下可用 . 您可以将其作为early as Python 2.5(但此时需要升级!):

    from __future__ import with_statement
    

    这里's the closest thing to correct that you have. You'几乎在那里,但 with 没有 except 条款:

    使用open(“a.txt”)作为f:
    打印(f.readlines())
    除了:#< - with没有except子句 .
    打印(“糟糕”)

    上下文管理器的 __exit__ 方法,如果它返回 False 将在完成时重新加载错误 . 如果它返回 True ,它将禁止它 . open 内置的 __exit__ 不返回 True ,所以你只需要在try中嵌套它,除了块:

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

    标准样板:不要使用__82767_来捕获 BaseException 以及其他所有可能的异常和警告 . 至少与 Exception 一样具体,对于这个错误,也许赶上 IOError . 只捕获您准备处理的错误 .

    所以在这种情况下,你会这样做:

    >>> try:
    ...     with open("a.txt") as f:
    ...         print(f.readlines())
    ... except IOError as error: 
    ...     print('oops')
    ... 
    oops
    
  • 60

    另一种方法是检查文件是否先存在,然后继续 with 语句 . 例:

    import os
    
    if not os.path.exists(file_path): # check first if file exsits
       print("file not found")
    
    else:
        with open("a.txt") as f: # proceed as usual
            print f.readlines()
    

相关问题