views:

1107

answers:

3

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...
+5  A: 

The Exception has a errno attribute:

try:
    fp = open("nother")
except IOError, e:
    print e.errno
    print e
stefanw
+3  A: 

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, ioex:
    print 'errno:', ioex.errno
    print 'err code:', errno.errorcode[ioex.errno]
    print 'err message:', os.strerror(ioex.errno)

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

ars
+2  A: 
try:
    fp = open("nothere")
except IOError as err:
    print err.errno 
    print err.strerror
Pavel Minaev