minion minion - 1 year ago 110
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'?

open('invalid path')
except OSError as e:
error = e

The results:

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

Answer Source

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'):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download