【问题标题】:Integrating exception handling in Python 'with' [duplicate]在 Python 'with' 中集成异常处理 [重复]
【发布时间】:2015-01-12 04:00:39
【问题描述】:

打开文件并读取其内容的简单方法是使用with

with open ('file.txt', "r") as filehandle:
    contents = filehandle.read()

但这不包括以 try/except 的方式排除文件打开错误:

try:
    filehandle = open('file.txt', 'r')
    contents = filehandle.read()
except IOError:
    print('There was an error opening the file!')
    sys.exit()

有没有办法将失败消息集成到 with 语句中,以便在打开失败时优雅退出,这将在比第二个示例更少的代码行中完成,但提供相同的功能?如果不是这样,还有什么比第二种形式更优雅(或极简)的吗?

【问题讨论】:

    标签: python exception-handling


    【解决方案1】:
    from contextlib import contextmanager
    
    @contextmanager
    def safe_open(fname,mode):
        try:
            fh = open(fname,mode)
        except IOError:
            print "ERROR OPENING FILE :",fname
            sys.exit()
        else:
            yield fh
            try:
                fh.close()
            except:
                pass
    
    
    with safe_open("nofile","rb") as f:
        f.write("blah")
    

    我不确定它是否更优雅,但嗯...

    【讨论】:

    • 这看起来不太优雅
    • 那只是因为你看到了实现......如果你只是做from util import safe_open......然后使用它。然后它非常优雅......(
    猜你喜欢
    • 1970-01-01
    • 2019-01-19
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多