Python异常处理

jr0*_*r0d 21 python exception errno ioerror

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...

ste*_*anw 32

Exception有一个errno属性:

try:
    fp = open("nothere")
except IOError as e:
    print(e.errno)
    print(e)
Run Code Online (Sandbox Code Playgroud)


ars*_*ars 27

这是你如何做到的.另请参阅某些实用程序的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)
Run Code Online (Sandbox Code Playgroud)

有关IOError属性的更多信息,请参阅基类EnvironmentError:


Pav*_*aev 21

try:
    fp = open("nothere")
except IOError as err:
    print err.errno 
    print err.strerror
Run Code Online (Sandbox Code Playgroud)

  • 这是现在的首选语法,对于那些现在查看此问题的人来说只是一个FYI ... (9认同)
  • 如果你在打印上使用大括号,则可以在python3中使用 (2认同)