Home > python > Call Python from C

Call Python from C

You want to embed Python code inside a C program.

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


#include "Python.h"

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


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
  1. July 1, 2013 at 11:24
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: