LanguagesEmbedding Python

Embedding Python content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

An earlier article demonstrated creating an extension for Python. This article focuses on embedding, which is a second way of integrating C and Python.

Embedding in Python is where C, or C++, or any program for that matter, is given direct access to the Python interpreter. This gives the program the power to load and execute Python scripts and services. In C, this enables you load in Python-specific modules, call Python functions, and access Python objects.

Embedding is powered by Python’s API, which can be used by including Python.h. This header contains all the functions, types, and macro definitions needed to use the API. It is fairly simple to initialize Python in C/C++ once the Python header file is included:

#include "Python.h"

int  main()

Py_Initialize is the basic initialization function and allocates resources for the interpreter to start using the API. In particular, it initializes and creates Python’s sys, exceptions, _builtin_, and _main_modules. Py_Initialize searches for modules, assuming that the Python library is in a fixed location (details that may need to be altered, depending on the operating system, by setting Python’s path and home). After initialization and running the code, Py_Finalize releases the internal resources and shuts down the interpreter.

The Pyrun_SimpleFile is simply one of the very high-level API functions that reads the given file from a pointer (FILE *) and executes the commands stored there. Python’s high-level API functions are basically just for executing given Python source, not interacting with it in any significant way. Other high-level functions include the following:


The high-level tools really just scratch the surface, and Python’s API allows memory management, creating objects, threading, and exception handling, to name a few. Other commonly used commands you will find include PyImport_ImportModule() for importing and initializing entire Python modules, PyObject_GetAttrString() for accessing a given modules attributes, and PyObject_SetAttrString() for assigning values to variables within modules.

The API reference manual by Guido is of course very well organized and documented, and the place you should research before using this powerful Python feature.


Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories