Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to raise Python exception from a C extension?

I have written a C extension and I want to raise a python exception from this code. Any help in this matter is appreciated.

#include 
static PyObject* helloworld(PyObject* self) {
return Py_BuildValue("s"+5 , "Hello, Python extensions!! Hi there! Whassup!");
}
static char helloworld_docs[] =
"helloworld( ): Hi there Whatssup!\
";
static PyMethodDef helloworld_funcs[] = {
{"helloworld", (PyCFunction)helloworld,
METH_NOARGS, helloworld_docs},
{NULL}
};
void inithelloworld(void) {
Py_InitModule3("helloworld", helloworld_funcs,
"Extension module example!");


1 Answer
Rajendra Dharmkar

For the above module, we need to prepare following setup.py script −

from distutils.core import setup, Extension
setup(name='helloworld', version='1.0', \
ext_modules=[Extension('helloworld', ['hello.c'])])

Now, we use the following command,

$ python setup.py install

Once we install the extension, we would be able to import and call that extension in our Python script test.py and catch the exception in it as follows −

#test.py
import helloworld
try:
print helloworld.helloworld()
except Exception as e:
print str(e)

This would produce the following result −

bad format char passed to Py_BuildValue
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.