Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the errno of an IOError?

Tags:

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... 
like image 443
jr0d Avatar asked Jul 15 '09 23:07

jr0d


People also ask

How do you catch IOError exception in Python?

It is an error raised when an input/output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. It is also raised for operating system-related errors.

What is IOError in Python?

IOError in Python is a result of incorrect file name or location. This error is raised in multiple conditions and all these conditions can be handled using try except code block.

How does Python handle IO exception?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.

What is the meaning of Errno Eexist?

errno. EEXIST. File exists. This error is mapped to the exception FileExistsError .


2 Answers

The Exception has an errno attribute:

try:     fp = open("nothere") except IOError as e:     print(e.errno)     print(e) 
like image 86
stefanw Avatar answered Oct 10 '22 04:10

stefanw


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
like image 33
ars Avatar answered Oct 10 '22 05:10

ars