Raising a specific OSError

Kelvie Wong kelvie at ieee.org
Fri Apr 21 20:22:20 EDT 2006


Looking at the Python docs.. I found this:
http://docs.python.org/ext/errors.html

"""
Another useful function is PyErr_SetFromErrno(), which only takes an
exception argument and constructs the associated value by inspection
of the global variable errno. The most general function is
PyErr_SetObject(), which takes two object arguments, the exception and
its associated value. You don't need to Py_INCREF() the objects passed
to any of these functions.
"""

So, in a C extension, to raise a a specific OSError...

errno = ENOENT;
PyErr_SetFromErrno(PyExc_OSError);

should work...

On 4/21/06, Kelvie Wong <kelvie at ieee.org> wrote:
> I do not see the point in doing so (why not just copy+paste that
> string?), but the errno (specifically ENOENT) corresponds to the
> POSIX.1 error number, and the string "No such file or directory" is
> done in C via strerror(ENOENT); (check errno(3) and strerror(3)).
>
> I doubt there is something that does this in the standard library
> (just checked, there's an errno module, but it is quite sparse), but a
> simple C extension would be trivial to write.
>
> However, the best way is just to copy and paste that text into your
> program, I mean, why not?
>
> raise OSError("[Errno 2] No such file or directory")
>
> On 4/21/06, David Hirschfield <davidh at ilm.com> wrote:
> >  I wasn't clear enough in my original post.
> >
> >  I know how to raise a basic OSError or IOError, but what if I want to raise
> > specifically an "OSError: [Errno 2] No such file or directory"?
> >  Somehow it must be possible to raise the error with the correct information
> > to bring up the standard message, but where do I find the right values to
> > give?
> >
> >  Thanks,
> >  -Dave
> >
> >
> >
> >  alisonken1 wrote:
> >  To raise a specific error, just find the error that you want to raise,
> > then give the error a text string to print: ex.
> >
> > raise IOError("This raises an IO error")
> >
> > On the stderr output, when the routine hits this line, you will get:
> >
> >
> >
> >
> >
> >  raise IOError("This raises an IOError")
> >
> >  Traceback (most recent call last):
> >  File "<stdin>", line 1, in ?
> > IOError: This raises an IOError
> >
> >
> >  Just be sure of the error that you want to raise, since some of them
> > will do stuff like closing open file descriptors as well.
> >
> >
> >
> >
> > --
> > Presenting:
> > mediocre nebula.
> >
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> >
>
>
> --
> Kelvie
>


--
Kelvie



More information about the Python-list mailing list