Is there any way to catch expections when call python method in C++

Robert Bauck Hamar roberth+news at ifi.uio.no
Wed Jun 13 11:03:00 EDT 2007


Allen wrote:

> I use try catch, but cannot catch the execeptions of execution python
> method.
> 
> PYCALL_API void PyCall(const char * pszModule, const char * pszFunc,
> void * pArg)
> {
> if (pszModule == NULL || pszFunc == NULL)
> {
> return;
> }
> 
> Py_Initialize();
> 
> PyObject * pModule = NULL;
> PyObject * pFunc   = NULL;
> 
>         try {
> 
> pModule = PyImport_ImportModule(pszModule);
> pFunc   = PyObject_GetAttrString(pModule, pszFunc);
> 
> PyEval_CallObject(pFunc, (PyObject*)pArg);
>         } catch (...) {
>            fprintf(stderr, "Error: call python method failed");
>         }
> 
> Py_Finalize();
> }
> 
> Can I catch it from C++?

No. CPython is written in C, not C++, and C has no concept of exceptions.
Exceptions in Python is usually indicated by return value in the
interpreter, and has no mapping to the C++ exception model. You should
never let C++ exceptions propagate into the python functions either.
PyImport_ImportModule will return NULL if an exception occured, and so will
also PyObject_GetAttrString and PyEval_CallObject do.

-- 
rbh



More information about the Python-list mailing list