I have a Python 3 program which calls a C function. The C function returns an integer: 0 upon success, or the appropriate errno
upon failure. Upon failure, the Python code could simply raise OSError
. But I'd rather it raise the appropriate subclass of OSError
.
For example, if the Python program gets the return code of 2, it should raise FileNotFoundError
, a subclass of OSError
. I can already find the correct subclass by doing the following three steps. Obviously, performance is not an issue because I need to do these steps only once per version of Python 3 for all values of errno
, and cache the results.
OSError
. This is easy using __subclass__
, recursively if necessary.errno
values to names. For example, if errno
is 2, that should map to ENOENT
. This is done by parsing the appropriate C include file. On FreeBSD, for example, that file would be /usr/include/errno.h
.errno
names to OSError
subclasses. This can be done by parsing the HTML code in, for example, http://docs.python.org/release/3.8.2/library/exceptions.htmlBut step 3 is really, really hokey. Is there a way I can do that step without parsing the documentation? Is there something I can inspect somehow in the Python that's sitting on my local host?
When you look at the documentation I believe that this translation is done automatically. if you for example call:
raise OSError(2, 'this went wrong') # here the 2 corresponds to the error given by C
# raises -> FileNotFoundError: [Errno 2] this went wrong
For the exact mapping used here go to the page you reference and look at the OS exceptions section.