Retrieving exception value in C

swapnil swapnil.st at gmail.com
Wed Dec 23 02:24:04 EST 2009


I am trying to retrieve the value of the exception (the message part)
raised in python, in C.

Running the below script,

import shutil
fd= open("testfile","w")
fd.write("some junk")
fd.close()
shutil.copy("testfile","testfile")

will generate an exception like this,

Traceback (most recent call last):
  File "C:\Python26\lib\myscript.py", line 10, in <module>
    shutil.copy("testfile","testfile")
  File "C:\Python26\lib\shutil.py", line 88, in copy
    copyfile(src, dst)
  File "C:\Python26\lib\shutil.py", line 47, in copyfile
    raise Error, "`%s` and `%s` are the same file" % (src, dst)
shutil.Error: `testfile` and `testfile` are the same file


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

Although I think its not required, FYI I'm running python 2.6.2 on
WinXP





More information about the Python-list mailing list