Python:捕获open()异常需要什么?

2024-05-15 21:53:50 发布

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

我正在用多个函数打开文件,保持“优雅地”处理潜在的IOErrors似乎有点混乱/多余:

try:  
    fileHandle = open(file, 'r')  
except:  
    print "Error: failed to open file %s" % (file)  
    sys.exit(2)

在什么情况下可以仅仅:

fileHandle = open(file, 'r')

并期望用户在异常情况下查看回溯消息?你知道吗


Tags: 文件to函数sysexit情况erroropen
3条回答

把你的应用程序包装成一个外部的try/除了打印一些更好的东西和记录血淋淋的细节。我没有在这里设置记录器,但你明白了:

import os
import sys
import logging
import traceback

try:
    my_application(params)
except (OSError, IOError), e:
    message = "%s - %s." % (e.filename, e.sterror)
    sys.stderr.write("Error: %s. See log file for details%s" % (message, os.linesep))
    logger.error('myapp', message)
    for line in traceback.format_exc().split(os.linesep):
        logger.warn('myapp', line)
    sys.exit(2)

这是用Python和其他语言实现的异常原则。对于引发异常的函数,不需要local中的异常处理。你知道吗

如果一些本地处理是有意义的,就去做。如果您不能做任何有用的事情,就让异常进入调用堆栈,直到找到合适的异常处理程序。你知道吗

http://docs.python.org/2/tutorial/errors.html#handling-exceptions


如果只是为了记录异常而捕获异常,则可能需要重新引发它:

try:  
    fileHandle = open(file, 'r')  
except IOError:  
    print "Error: failed to open file %s" % (file, )  
    raise

http://docs.python.org/2/tutorial/errors.html#raising-exceptions

使用“with”关键字。你知道吗

with open(file, 'r') as fileHandle:
    do_whatever()

此代码或多或少相当于

try:
    fileHandle = open(file, 'r')
except IOError:
    pass
else: 
    do_whatever()
finally:
    fileHandle.close()

基本上,它确保您正确地打开和关闭文件,并捕获异常。你知道吗

相关问题 更多 >