Boost Python Embedded Example

The reason to call Python inside C++ program is I want to use PyQt for UI stuff. This document is intended to show how to build a minimal example to embed Python in C++ using Boost Python, on Max OS X.

To make this working, one should install a few programs in the system, including: Python, Qt, PyQt, and Boost.

For Leopard, the built-in Python is 2.5, which is too old to work with PyQt. Need update to 2.6. I would prefer to  download the tar ball of Python source and build myself:

$ ./configure --enable-framework

$ make

$ make install

When framework is enabled, Python will be built into


Now you have multiple versions of Python in the system, probably you are still using the old one. To make sure it is up-to-date, start Python, type:

import sys


Should return


This is what Python you are using. Type:


Should return a string array about where the Python is searching for modules, should include:


If you are getting ‘/usr/local/’ stuff, means you are still calling the old Python. To work round this, add environment value


to explicitly choose the version just installed. Now one can build PyQt and Boost.

Create the source file Main.cpp:

#include <boost/python.hpp>
#include <iostream>
using namespace std;
using namespace boost::python;

int main()
 cout<<"hello boost python embedded "<<endl;

cout<<"version "<<Py_GetVersion()<<endl;

PyRun_SimpleString("from time import time,ctime\n"
 "print 'Today is',ctime(time())\n");
FILE *file_1 = fopen("./","r+");


return 0;

Compile it by Makefile:


 g++ -o test main.cpp -I$(PYTHON_INC) -I$(BOOST_INC) -L$(BOOST_LIB) -lboost_python -framework Python

Still need the file to call from the test program, I just use the form PyQt tutorial examples. But for some reason

app = QtGui.QApplication(sys.argv)

doesn’t work. I have to change it to

app = QtGui.QApplication(sys.path)

If everything works out, the program is compiled, run it, a little window will pop up:

Well done! It is the first time you call Python inside a C++ program.


Leave a comment

Filed under Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s