Python异常处理

C有perror和errno,它们打印并存储遇到的最后一个错误。 这在做文件io时很方便,因为我不必为每个失败的文件fstat()作为fopen()的参数来向用户展示调用失败的原因。

我想知道在python中正常处理IOError异常时,抓取errno的正确方法是什么?

In [1]: fp = open("/notthere")
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)

/home/mugen/ in ()

IOError: [Errno 2] No such file or directory: '/notthere'


In [2]: fp = open("test/testfile")
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)

/home/mugen/ in ()

IOError: [Errno 13] Permission denied: 'test/testfile'


In [5]: try:
   ...:     fp = open("nothere")
   ...: except IOError:
   ...:     print "This failed for some reason..."
   ...:     
   ...:     
This failed for some reason...

该异常具有errno属性:

try:
    fp = open("nothere")
except IOError as e:
    print(e.errno)
    print(e)

这是你如何做到的。 对于某些实用程序,另请参阅errno模块和os.strerror函数。

import os, errno

try:
    f = open('asdfasdf', 'r')
except IOError as ioex:
    print 'errno:', ioex.errno
    print 'err code:', errno.errorcode[ioex.errno]
    print 'err message:', os.strerror(ioex.errno)
  • http://docs.python.org/library/errno.html
  • http://docs.python.org/library/os.html
  • 有关IOError属性的更多信息,请参阅基类EnvironmentError:

  • http://docs.python.org/library/exceptions.html?highlight=ioerror#exceptions.EnvironmentError

  • try:
        fp = open("nothere")
    except IOError as err:
        print err.errno 
        print err.strerror
    
    链接地址: http://www.djcxy.com/p/9253.html

    上一篇: Python Exception handling

    下一篇: Cross platform patching