Archive

Posts Tagged ‘embed Python in C’

Call Python from C

July 1, 2013 1 comment

Problem
You want to embed Python code inside a C program.

Solution
See this: http://docs.python.org/2/extending/embedding.html.

Example:

#include "Python.h"

int main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n");
  Py_Finalize();
  return 0;
}

Compilation:

gcc -I/usr/include/python2.7 cool.c -lpython2.7
# or:
clang -I/usr/include/python2.7 -lpython2.7 cool.c

Sample output:

Today is Mon Jul  1 00:53:10 2013

For more details, please refer to this page.

Update (20140216)
I tried this example today and clang dropped me this error:

/usr/include/limits.h:124:16: fatal error: 'limits.h' file not found

I have Clang 3.2 on my machine and it’s a known bug. There is a workaround:

$ cd /usr/lib/clang/3.2/
$ sudo ln -s /usr/lib/llvm-3.2/lib/clang/3.2/include

Update (20200202)
Today I tried it with Python 3.8. Docs: https://docs.python.org/3/extending/embedding.html . Sample source code:

#define PY_SSIZE_T_CLEAN
#include 

int main(int argc, char *argv[])
{
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    Py_SetProgramName(program);  /* optional but recommended */
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
                       "print('Today is', ctime(time()))\n");
    if (Py_FinalizeEx() < 0) {
        exit(120);
    }
    PyMem_RawFree(program);
    return 0;
}

Compilation and execution:

$ gcc -I/usr/include/python3.8 call.c -lpython3.8 -o call
$ ./call
Today is Sun Feb  2 19:48:28 2020

It also works with clang, just replace “gcc” with “clang”.