Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSError's filename attribute unavailable?

I have the following code:

except(OSError) as (errno, strerror, filename):
print "OSError [%d]: %s at %s" % (errno, strerror, filename)

It runs great unless it meets OSError num. 123 (The file name, directory name, or volume label syntax is incorrect). then I get the following error at the except code line:

ValueError: need more than 2 values to unpack

It is solved by not using the filename attribute. However my requirements prevent me from not using this attribute.

Is there another way?

like image 898
Alex58 Avatar asked Jan 13 '11 15:01

Alex58


People also ask

Why does oserror (errno 22) invalid argument occur?

The OSError: (errno 22) invalid argument occurs may also occur when one is trying to save a file. For example: adding an unnecessary semicolon to the filename also causes the error. It is because windows do not allow semi-colons in file names. That was it for OSError: (errno 22) invalid argument.

Is there a subclass for fileexistserror when the filename is too long?

When handling the errors that occur when trying to create an existing file or trying to use a file that doesn't exist the OSError s that get thrown have a subclass ( FileExistsError, FileNotFoundError ). I couldn't find that subclass for the special case when the filename is too long.

Why do I get error 22 when saving a file?

A. The OSError: (errno 22) invalid argument occurs may also occur when one is trying to save a file. For example: adding an unnecessary semicolon to the filename also causes the error. It is because windows do not allow semi-colons in file names.

What is oserror in Python?

OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as “file not found” or “disk full”. Below is an example of OSError: Attention geek!


1 Answers

I have not seen this kind of Exception handling where you are passing the Exception object's attributes to the as clause.

Normally you handle except ExceptionObject as e and handle the attributes as one would normally handle the attributes of an object.

OSError contains a errno attribute is a numeric error code from errno, and the strerror attribute is the corresponding string and for exceptions that involve a file system path (such as chdir() or unlink()), the exception instance will contain a third attribute, filename, which is the file name passed to the function.

import os
try:
    os.chdir('somenonexistingdir')
except OSError as e:
    print e.errno
    print e.filename
    print e.strerror
like image 108
Senthil Kumaran Avatar answered Oct 02 '22 15:10

Senthil Kumaran