minion minion - 1 month ago 5
Python Question

How to get Exception OSError 's third arguments?

From Python document:


For backwards compatibility, if three arguments are passed, the args attribute contains only a 2-tuple of the first two constructor arguments.


So How do we I the third arguments, like the 'invalid path'?

try:
open('invalid path')
except OSError as e:
error = e
print(error.args[0],error.args[1])
print(e)


The results:

2 No such file or directory
[Errno 2] No such file or directory: 'invalid path'

Answer

From the same docs:

For exceptions that involve a file system path (such as open() or os.unlink()), filename is the file name passed to the function. For functions that involve two file system paths (such as os.rename()), filename2 corresponds to the second file name passed to the function.

So you simply do error.filename, because filename is an optional arg which only gets passed for certain types of errors.

To make a one for all check, you can use hasattr:

if hasattr(error, 'filename'):
    print(error.filename)
Comments