En Wed, 23 Dec 2009 04:24:04 -0300, swapnil <swapnil...@gmail.com>
escribió:
I am trying to retrieve the value of the exception (the message part)
raised in python, in C.
But if I run (actually import) the script from within a C code
(embedding python in C), I am able to get the exception object but not
the value.
The code looks like,
int main()
{
PyObject *exc, *val, *tbk, *module, *name;
PyObject *exc_str;
Py_Initialize();
name = PyString_FromString("myscript");
module = PyImport_Import(name);
Py_DECREF(name);
if(!module)
{
printf("error in running script\n");
if( PyErr_Occurred())
{
if(PyErr_ExceptionMatches(PyExc_Exception))
{
printf("exception received in C\n");
}
PyErr_Fetch(&exc, &val, &tbk);
exc_str = PyObject_Str(exc);
printf("exception received: %s\n", PyString_AsString(exc_str));
printf("exception value: %s\n",PyString_AsString(val));
Py_DECREF(exc_str);
Py_DECREF(exc);
Py_DECREF(val);
Py_DECREF(tbk);
}
else{
printf("no exception received in C\n");
}
}
Py_XDECREF(module);
PyErr_Clear();
Py_Finalize();
return 0;
}
I get output,
error in running script
exception received in C
exception received: <class 'shutil.Error'>
exception value: (null)
While the last line should be,
exception value: `testfile` and `testfile` are the same file
PyErr_fetch retrieves the exception *type*, the exception *instance*, and
the traceback. So in your code exc is shutil.Error (the class) and val is
the specific instance raised.
The NULL comes from PyString_AsString(val) - it fails because val is not a
string object.
In Python code you'd get the message using str(val) - that would be
written PyObject_Str(val) in C.
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list