Intégrer Python dans une autre application

Les chapitres précédents couvraient l'extension de Python, c'est-à-dire, comment enrichir une fonctionnalité de Python en y attachant une bibliothèque de fonctions C. C'est aussi possible dans l'autre sens : enrichir vos applications C/C++ en y intégrant Python. Intégrer Python vous permet d'implémenter certaines fonctionnalités de vos applications en Python plutôt qu'en C ou C++. C'est utile dans de nombreux cas, un exemple serait de permettre aux utilisateurs d'adapter une application à leurs besoins en y écrivant des scripts Python. Vous pouvez aussi l'utiliser vous même si certaines fonctionnalités peuvent être rédigées plus facilement en Python.

Intégrer et étendre Python sont des tâches presque identiques. La différence est qu'en étendant Python, le programme principal reste l'interpréteur Python, alors qu'en intégrant Python le programme principal peut ne rien à voir avec Python. C'est simplement quelques parties du programme qui appellent l'interpréteur Python pour exécuter un peu de code Python.

En intégrant Python, vous fournissez le programme principal. L'une de ses tâches sera d'initialiser l'interpréteur. Au minimum vous devrez appeler Py_Initialize(). Il est possible, avec quelques appels supplémentaires, de passer des options à Python. Ensuite vous pourrez appeler l'interpréteur depuis n'importe quelle partie de votre programme.

Il existe différents moyens d'appeler l'interpréteur : vous pouvez donner une chaîne contenant des instructions Python à PyRun_SimpleString(), ou vous pouvez donner un pointeur de fichier stdio et un nom de fichier (juste pour nommer les messages d'erreur) à PyRunSimpleFile(). Vous pouvez aussi appeler les API de bas niveau décrites dans les chapitres précédents pour construire et utiliser des objets Python.

Voir aussi

Python/C API reference manual

Les détails sur l'interface entre Python et le C sont donnés dans ce manuel. Pléthore informations s'y trouvent.

Intégration de très haut niveau

La manière la plus simple d'intégrer Python est d'utiliser une interface de très haut niveau. Cette interface a pour but d'exécuter un script Python sans avoir à interagir avec directement. C'est utile, par exemple, pour effectuer une opération sur un fichier.

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc, char *argv[])
{
    PyStatus status;
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    /* optional but recommended */
    status = PyConfig_SetBytesString(&config, &config.program_name, argv[0]);
    if (PyStatus_Exception(status)) {
        goto exception;
    }

    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) {
        goto exception;
    }
    PyConfig_Clear(&config);

    PyRun_SimpleString("from time import time,ctime\n"
                       "print('Today is', ctime(time()))\n");
    if (Py_FinalizeEx() < 0) {
        exit(120);
    }
    return 0;

  exception:
     PyConfig_Clear(&config);
     Py_ExitStatusException(status);
}

Note

#define PY_SSIZE_T_CLEAN was used to indicate that Py_ssize_t should be used in some APIs instead of int. It is not necessary since Python 3.13, but we keep it here for backward compatibility. See Chaînes et tampons for a description of this macro.

Setting PyConfig.program_name should be called before Py_InitializeFromConfig() to inform the interpreter about paths to Python run-time libraries. Next, the Python interpreter is initialized with Py_InitializeFromConfig(), followed by the execution of a hard-coded Python script that prints the date and time. Afterwards, the Py_FinalizeEx() call shuts the interpreter down, followed by the end of the program. In a real program, you may want to get the Python script from another source, perhaps a text-editor routine, a file, or a database. Getting the Python code from a file can better be done by using the PyRun_SimpleFile() function, which saves you the trouble of allocating memory space and loading the file contents.

Au-delà de l'intégration de haut niveau : survol

L'interface de haut niveau vous permet d'exécuter n'importe quel morceau de code Python depuis votre application, mais échanger des données est quelque peu alambiqué. Si c'est ce dont vous avez besoin, vous devez utiliser des appels de niveau plus bas. Il vous en coûtera plus de lignes de C à écrire, mais vous pourrez presque tout faire.

Il est à souligner qu'étendre ou intégrer Python revient à la louche au même, en dépit de la différence d'intention. La plupart des sujets parcourus dans les chapitres précédents sont toujours valides. Pour le prouver, regardez ce qu'un code d'extension de Python vers C fait réellement :

  1. Convertir des valeurs de Python vers le C,

  2. Appeler une fonction C en utilisant les valeurs converties, et

  3. Convertir les résultats de l'appel à la fonction C pour Python.

Lors de l'intégration de Python, le code de l'interface fait :

  1. Convertir les valeurs depuis le C vers Python,

  2. Effectuer un appel de fonction de l'interface Python en utilisant les valeurs converties, et

  3. Convertir les valeurs de l'appel Python pour le C.

Tel que vous le voyez, les conversions sont simplement inversées pour s'adapter aux différentes directions de transfert inter-langage. La seule différence est la fonction que vous appelez entre les deux conversions de données. Lors de l'extension, vous appelez une fonction C, lors de l'intégration vous appelez une fonction Python.

Ce chapitre ne couvrira pas la conversion des données de Python vers le C ni l'inverse. Aussi, un usage correct des références, ainsi que savoir gérer les erreurs sont considérés acquis. Ces aspects étant identiques à l'extension de l'interpréteur, vous pouvez vous référer aux chapitres précédents.

Intégration pure

L'objectif du premier programme est d'exécuter une fonction dans un script Python. Comme dans la section à propos des interfaces de haut niveau, l'interpréteur n'interagit pas directement avec l'application (mais le fera dans la section suivante).

Le code pour appeler une fonction définie dans un script Python est :

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();
    pName = PyUnicode_DecodeFSDefault(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyLong_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    if (Py_FinalizeEx() < 0) {
        return 120;
    }
    return 0;
}

Ce code charge un script Python en utilisant argv[1], et appelle une fonction dont le nom est dans argv[2]. Ses arguments entiers sont les autres valeurs de argv. Si vous compilez et liez ce programme (appelons l'exécutable call), et l'appelez pour exécuter un script Python, tel que :

def multiply(a,b):
    print("Will compute", a, "times", b)
    c = 0
    for i in range(0, a):
        c = c + b
    return c

alors, le résultat sera :

$ call multiply multiply 3 2
Will compute 3 times 2
Result of call: 6

Bien que le programme soit plutôt gros pour ses fonctionnalités, la plupart du code n'est que conversion de données entre Python et C, aussi que pour rapporter les erreurs. La partie intéressante, qui concerne l'intégration de Python débute par :

Py_Initialize();
pName = PyUnicode_DecodeFSDefault(argv[1]);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);

After initializing the interpreter, the script is loaded using PyImport_Import(). This routine needs a Python string as its argument, which is constructed using the PyUnicode_DecodeFSDefault() data conversion routine.

pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */

if (pFunc && PyCallable_Check(pFunc)) {
    ...
}
Py_XDECREF(pFunc);

Une fois le script chargé, le nom recherché est obtenu en utilisant PyObject_GetAttrString(). Si le nom existe, et que l'objet récupéré peut être appelé, vous pouvez présumer sans risque que c'est une fonction. Le programme continue, classiquement, par la construction de n-uplet d'arguments. L'appel à la fonction Python est alors effectué avec :

pValue = PyObject_CallObject(pFunc, pArgs);

Après l'exécution de la fonction, pValue est soit NULL, soit une référence sur la valeur donnée par la fonction. Assurez-vous de libérer la référence après avoir utilisé la valeur.

Étendre un Python intégré

Jusqu'à présent, l'interpréteur Python intégré n'avait pas accès aux fonctionnalités de l'application elle-même. L'API Python le permet en étendant l'interpréteur intégré. Autrement dit, l'interpréteur intégré est étendu avec des fonctions fournies par l'application. Bien que cela puisse sembler complexe, ce n'est pas si dur. Il suffit d'oublier que l'application démarre l'interpréteur Python, au lieu de cela, voyez l'application comme un ensemble de fonctions, et rédigez un peu de code pour exposer ces fonctions à Python, tout comme vous écririez une extension Python normale. Par exemple :

static int numargs=0;

/* Return the number of arguments of the application command line */
static PyObject*
emb_numargs(PyObject *self, PyObject *args)
{
    if(!PyArg_ParseTuple(args, ":numargs"))
        return NULL;
    return PyLong_FromLong(numargs);
}

static PyMethodDef emb_module_methods[] = {
    {"numargs", emb_numargs, METH_VARARGS,
     "Return the number of arguments received by the process."},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef emb_module = {
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "emb",
    .m_size = 0,
    .m_methods = emb_module_methods,
};

static PyObject*
PyInit_emb(void)
{
    return PyModuleDef_Init(&emb_module);
}

Insérez le code ci-dessus juste avant la fonction main(). Ajoutez aussi les deux instructions suivantes avant l'appel à Py_Initialize() :

numargs = argc;
PyImport_AppendInittab("emb", &PyInit_emb);

These two lines initialize the numargs variable, and make the emb.numargs() function accessible to the embedded Python interpreter. With these extensions, the Python script can do things like

import emb
print("Number of arguments", emb.numargs())

Dans un cas réel, les méthodes exposeraient une API de l'application à Python.

Intégrer Python dans du C++

Il est aussi possible d'intégrer Python dans un programme en C++, la manière exacte dont cela se fait dépend de détails du système C++ utilisé. En général vous écrirez le programme principal en C++, utiliserez un compilateur C++ pour compiler et lier votre programme. Il n'y a pas besoin de recompiler Python en utilisant C++.

Compiler et Lier en environnement Unix ou similaire

Ce n'est pas évident de trouver les bonnes options à passer au compilateur (et linker) pour intégrer l'interpréteur Python dans une application, Python ayant besoin de charger des extensions sous forme de bibliothèques dynamiques en C (des .so) pour se lier avec.

Pour trouver les bonnes options de compilateur et linker, vous pouvez exécuter le script pythonX.Y-config généré durant l'installation (un script python3-config peut aussi être disponible). Ce script a quelques options, celles-ci vous seront utiles :

  • pythonX.Y-config --cflags vous donnera les options recommandées pour compiler :

    $ /opt/bin/python3.11-config --cflags
    -I/opt/include/python3.11 -I/opt/include/python3.11 -Wsign-compare  -DNDEBUG -g -fwrapv -O3 -Wall
    
  • pythonX.Y-config --ldflags --embed vous donnera les drapeaux recommandés lors de l'édition de lien :

    $ /opt/bin/python3.11-config --ldflags --embed
    -L/opt/lib/python3.11/config-3.11-x86_64-linux-gnu -L/opt/lib -lpython3.11 -lpthread -ldl  -lutil -lm
    

Note

Pour éviter la confusion entre différentes installations de Python, (et plus spécialement entre celle de votre système et votre version compilée), il est recommandé d'utiliser un chemin absolu vers pythonX.Y-config, comme dans l'exemple précédent.

Si cette procédure ne fonctionne pas pour vous (il n'est pas garanti qu'elle fonctionne pour toutes les plateformes Unix, mais nous traiteront volontiers les rapports de bugs), vous devrez lire la documentation de votre système sur la liaison dynamique (dynamic linking) et / ou examiner le Makefile de Python (utilisez sysconfig.get_makefile_filename() pour trouver son emplacement) et les options de compilation. Dans ce cas, le module sysconfig est un outil utile pour extraire automatiquement les valeurs de configuration que vous voudrez combiner ensemble. Par exemple :

>>> import sysconfig
>>> sysconfig.get_config_var('LIBS')
'-lpthread -ldl  -lutil'
>>> sysconfig.get_config_var('LINKFORSHARED')
'-Xlinker -export-dynamic'

Linking for one or several Python versions on Linux

The flags obtained from pythonX.Y-config --ldflags --embed link the application against one minor version of Python. If that Python was built as a shared library, the executable records a dependency on the versioned library, such as libpython3.12.so.1.0, and expected that specific minor version at runtime. This is the recommended setup for most host (embedding) applications. Build the application for each Python version that it supports, or distribute it together with the Python that it was built with.

Using the Limited API does not change this. Defining Py_LIMITED_API restricts your source code to API that is compatible across minor versions, but the library dependency is recorded when linking, so the executable still requires libpython3.12.so.1.0.

A binary that needs to run with several minor Python versions must use only the Limited API and must also avoid the versioned dependency.

Avertissement

Host applications that use the Limited API must be aware of the following limitations:

  • It can only initialize Python with Py_Initialize() or Py_InitializeEx(), which set Python up much like the python command does. They honor PYTHONHOME and PYTHONPATH, add the user site-packages directory to sys.path, and terminate the process if initialization fails. They set sys.executable to the python3 program found on PATH, which can belong to a different Python installation than the library that was loaded. The functions that accept an isolated configuration, Py_InitializeFromConfig() and Py_InitializeFromInitConfig(), are not part of the Limited API.

  • The Python that gets loaded is only known at run-time. Checking that it is suitable is up to the application. An incompatible Python, such as a too-old or too-new version, is not rejected automatically.

  • The Stable ABI keeps functions available in later versions, but it does not guarantee identical behavior. The default configuration and the way sys.path is computed can change between Python versions, and between installations of the same version. Test the application with every Python version and installation that it is meant to support. See also Stable ABI Caveats.

A Python built with --enable-shared and without --with-pydebug installs libpython3.so next to the versioned library. When the dynamic loader loads this library, it also loads the versioned library that it was built with, and symbols looked up through libpython3.so are found in the versioned library. An application can therefore load libpython3.so with dlopen(3) and look up each function that it uses with dlsym(3).

This only works at run time. When linking an executable, the linker does not use the dependencies of a library to resolve symbols, and libpython3.so defines no Python symbols of its own, so linking with -lpython3 fails with undefined reference errors.

For example, with Python 3.12 as the oldest supported version:

#define Py_LIMITED_API 0x030c0000  /* Limited API 3.12 */
#include <Python.h>
#include <dlfcn.h>
#include <stdio.h>

/* The API this application uses, declared as in Python.h.
   Everything is reached through these pointers. */
static struct {
    const unsigned long *Version;
    const char *(*GetVersion)(void);
    void (*InitializeEx)(int);
    int (*FinalizeEx)(void);
} py;

#define LOAD(lib, pointer, name) \
    ((*(void **)&(pointer) = dlsym(lib, name)) != NULL)

int
main(int argc, char *argv[])
{
    /* For brevity, the path comes from the command line.  A real
       application reads it from its own configuration. */
    if (argc != 2 || argv[1][0] != '/') {
        fprintf(stderr, "usage: %s /absolute/path/to/libpython3.so\n",
                argv[0]);
        return 2;
    }
    /* RTLD_GLOBAL is required: it lets the extension modules that
       Python imports find Python's symbols. */
    void *lib = dlopen(argv[1], RTLD_NOW | RTLD_GLOBAL);
    if (lib == NULL) {
        fprintf(stderr, "Python is not available: %s\n", dlerror());
        return 1;
    }
    if (!LOAD(lib, py.Version, "Py_Version")
        || !LOAD(lib, py.GetVersion, "Py_GetVersion")
        || !LOAD(lib, py.InitializeEx, "Py_InitializeEx")
        || !LOAD(lib, py.FinalizeEx, "Py_FinalizeEx"))
    {
        fprintf(stderr, "Unsupported Python: %s\n", dlerror());
        return 1;
    }
    if (*py.Version < Py_LIMITED_API) {
        fprintf(stderr, "Python %s is older than 3.12\n", py.GetVersion());
        return 1;
    }

    py.InitializeEx(0);
    printf("Loaded Python %s\n", py.GetVersion());
    return py.FinalizeEx() < 0 ? 120 : 0;
}

Compile the program with Python's headers, but without the output of --ldflags:

$ gcc $(/opt/bin/python3.12-config --includes) -o myapp myapp.c
$ ./myapp /usr/local/lib/libpython3.so
Loaded Python 3.14.10 (main, Nov  5 2026, 09:47:10) [GCC 14.2.0]

No Python library is passed to the linker, so the executable does not depend on one. You can check this with readelf:

$ readelf -d myapp | grep NEEDED
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]

For the same reason, Python functions can only be called through such pointers. This includes the functions that macros in Python.h expand to: for example, call Py_DecRef() through a pointer instead of using Py_DECREF().

  • The path passed to dlopen() selects the code that runs in your process. It should come from a trusted source and name a file that only trusted users can replace.

  • Use an absolute path. The dynamic loader looks for a name without a slash in its usual search path, such as LD_LIBRARY_PATH and the system library directories. It looks for the versioned library that libpython3.so depends on in the same way, and not next to libpython3.so. To choose the exact file, pass the absolute path of the versioned library to dlopen() instead.

  • RTLD_GLOBAL is required. Extension modules are generally not linked against a Python library, so Python can only import them if its symbols are visible globally.

Unsupported workaround: renaming the dependency after linking

Some applications are instead linked against a versioned library as described above, and the dependency recorded in the executable is then renamed to libpython3.so, for example with patchelf.

Avertissement

Renaming the dependency this way is unsupported. Nothing checks that such an executable only uses the Stable ABI, and it can contain copies of Python data, such as PyLong_Type, whose size differs between Python versions.