How to get the errno of an IOError?

喜你入骨 提交于 2019-12-20 09:46:14

问题


C has perror and errno, which print and store the last error encountered. This is convenient when doing file io as I do not have to fstat() every file that fails as an argument to fopen() to present the user with a reason why the call failed.

I was wondering what is the proper way to grab errno when gracefully handling the IOError exception in python?

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

回答1:


The Exception has an errno attribute:

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



回答2:


Here's how you can do it. Also see the errno module and os.strerror function for some utilities.

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

For more information on IOError attributes, see the base class EnvironmentError:

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



回答3:


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



回答4:


Different exceptions can also be tested for in the same 'except' clause, e.g.

try:
    serial_port.open()
except (AttributeError, SerialException) as e:
    print('cannot open serial port: {}'.format(e))


来源:https://stackoverflow.com/questions/1134607/how-to-get-the-errno-of-an-ioerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!