Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import and use standard Python module from inside Python C extension

I have Python extension module written in C. I want to use in this C code one of the standard Python modules, for example os or shutil. How is best to do this?

like image 960
zaharpopov Avatar asked Feb 11 '12 04:02

zaharpopov


People also ask

How do I access a module written in Python from C?

You need include Python. h header file in your C source file, which gives you access to the internal Python API used to hook your module into the interpreter. Make sure to include Python. h before any other headers you might need.

What is the standard extension for Python modules?

You'll need a file called setup.py to install your application. For this tutorial, you'll be focusing on the part specific to the Python C extension module.

What is needed for C extension?

Building C and C++ Extensions with distutils. Extension modules can be built using distutils, which is included in Python. Since distutils also supports creation of binary packages, users don't necessarily need a compiler and distutils to install the extension.


1 Answers

PyObject* os = PyImport_ImportModuleNoBlock("os");
if (os == NULL)
  return NULL;
someattr = PyObject_GetAttrString(os, "someattr");
Py_DECREF(os);

If you import the module only once e.g., in init_yourmodule() function then use PyImport_ImportModule("os").

like image 175
jfs Avatar answered Nov 14 '22 22:11

jfs