Embedding Python in Your C Programs
Listing 3. Making a Copy of the Environment
// Get a reference to the main module.
PyObject* main_module =
PyImport_AddModule("__main__");
// Get the main module's dictionary
// and make a copy of it.
PyObject* main_dict =
PyModule_GetDict(main_module);
PyObject* main_dict_copy =
PyDict_Copy(main_dict);
// Execute two different files of
// Python code in separate environments
FILE* file_1 = fopen("file1.py", "r");
PyRun_File(file_1, "file1.py",
Py_file_input,
main_dict, main_dict);
FILE* file_2 = fopen("file2.py", "r");
PyRun_File(file_2, "file2.py",
Py_file_input,
main_dict_copy, main_dict_copy);
I'll get into the details of how PyRun_File() works in a little bit, but if you look carefully at Listing 3, you should notice something interesting. When I call PyRun_File() to execute the files, the dictionary gets passed in twice. The reason for this is that Python code actually has two environmental contexts when it is executed. The first is the global context, which I've already talked about. The second context is the local context, which contains any locally defined variables or functions. In this case, those are the same, because the code being executed is top-level code. On the other hand, if you were to execute a function dynamically using multiple C-level calls, you might want to create a local context and use that instead of the global dictionary. For the most part though, it's generally safe to pass the global environment for both the global and local parameters.
At this point, I'm sure you've noticed the Py_DECREF() calls that popped up in the Listing 3 example. Those fun little guys are there for memory management purposes. Inside the interpreter, Python handles memory management automatically by keeping track of all references to memory transparent to the programmer. As soon as it determines that all references to a given chunk of memory have been released, it deallocates the no-longer needed chunk. This can be a problem when you start working on the C side though. Because C is not a memory-managed language, as soon as a Python data structure ends up referenced from C, all ability to track the references automatically is lost to Python. The C application can make as many copies of the reference that it wants, and hold on to it indefinitely without Python knowing anything about it.
The solution is to have C code that gets a reference to a Python object handle all of the reference counting manually. Generally, when a Python call hands an object out to a C program, it increments the reference count by one. The C code can then do what it likes with the object without worrying that it will be deleted out from under it. Then when the C program is done with the object, it is responsible for releasing its reference by making a call to Py_DECREF().
It's important, though, to remember when you copy a pointer within your C program that may outlast the pointer from which you're copying, you need to increment the reference count manually, by calling Py_INCREF(). For example, if you make a copy of a PyObject pointer to store inside an array, you'll probably want to call Py_INCREF() to ensure that the pointed-to object won't get garbage-collected after the original PyObject reference is decremented.
Now let's take a look at a slightly more useful example to see how Python can be embedded into a real program. If you take a look at Listing 4, you'll see a small program that allows the user to specify short expressions on the command line. The program then calculates the results of those expressions and displays them in the output. To add a little spice to the mix, the program also lets users specify a file of Python code that will be loaded before the expressions are executed. This way, the user can define functions that will be available to the command-line expressions.
Listing 4. A Simple Expression Calculator
#include <python2.3/Python.h>
void process_expression(char* filename,
int num,
char** exp)
{
FILE* exp_file;
// Initialize a global variable for
// display of expression results
PyRun_SimpleString("x = 0");
// Open and execute the file of
// functions to be made available
// to user expressions
exp_file = fopen(filename, "r");
PyRun_SimpleFile(exp_file, exp);
// Iterate through the expressions
// and execute them
while(num--) {
PyRun_SimpleString(*exp++);
PyRun_SimpleString("print x");
}
}
int main(int argc, char** argv)
{
Py_Initialize();
if(argc != 3) {
printf("Usage: %s FILENAME EXPRESSION+\n");
return 1;
}
process_expression(argv[1], argc - 1, argv + 2);
return 0;
}
Two basic Python API functions are used in this program, PyRun_SimpleString() and PyRun_AnyFile(). You've seen PyRun_SimpleString() before. All it does is execute the given Python expression in the global environment. PyRun_SimpleFile() is similar to the PyRun_File() function that I discussed earlier, but it runs things in the global environment by default. Because everything is run in the global environment, the results of each executed expression or group of expressions will be available to those that are executed later.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
- RSS Feeds
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Download the Free Red Hat White Paper "Using an Open Source Framework to Catch the Bad Guy"
- Tech Tip: Really Simple HTTP Server with Python
- Home, My Backup Data Center
- Android is Linux -- why no better inter-operation
50 min 1 sec ago - Connecting Android device to desktop Linux via USB
1 hour 18 min ago - Find new cell phone and tablet pc
2 hours 16 min ago - Epistle
3 hours 45 min ago - Automatically updating Guest Additions
4 hours 54 min ago - I like your topic on android
5 hours 40 min ago - Reply to comment | Linux Journal
6 hours 1 min ago - This is the easiest tutorial
12 hours 16 min ago - Ahh, the Koolaid.
17 hours 54 min ago - git-annex assistant
23 hours 54 min ago




Comments
Python Conference: PyCon 2006
For people that want to learn more about Python, especially those near Dallas Texas, I want to mention the upcoming community-organized annual Python conference, PyCon 2006.
Thanks!
Higher level interfaces
The Python/C API is very low level, verbose, painful to work with, and highly error prone. With C++ code in particular it just sucks - you'll spend half your time writing const_cast("blah") to work around "interesting" APIs or writing piles of "extern C" wrapper functions, and the rest of your time writing verbose argument encoding/decoding or reference counting code. It's immensely frustraing to use plain C to write a Python object to wrap a C++ object.
Do yourself a favour, and once you've got embedding working, expose the Python interface to your program using a higher level tool. I hear SWIG is pretty good, especially for plain C code, but haven't used it myself (I work with heavily templated C++ with Qt). SIP (used to make PyQt) from Riverbank computing has its advantages also, and is good if you want your Qt app's API to integrate cleanly into PyQt. Otherwise, I'd suggest the amazing Boost::Python for C++ users, as it's ability to almost transparently wrap your C++ interfaces, mapping them to quite sensible Python semantics, is pretty impressive.
Boost::Python has the added advantage that you can write some very nice C++ code that integrates cleanly with Python. For example, you can iterate over a Python list much like a C++ list, throw exceptions between C++ and Python, build Python lists as easily as (oversimplified example):
#include <boost/python.hpp>
using namespace boost::python;
boost::python::list make_list()
{
list pylist;
for (int i = 0; i != 10; ++i)
pylist.append( make_tuple( "fred", 10 ) );
return pylist;
}
The equivalent Python/C API code is longer, filled with dangerous reference count juggling, contains a lot of manual error checking that's often ignored, and is a lot uglier.
With regards to the article above, it's good to see things like this written. I had real trouble getting started with embedding Python, and I think this is a pretty well written intro. I do take issue with one point, though, and that's duplicating the environment. Cloning the main dict does not provide separate program environments - very far from it. It only gives them different global namespaces. Interpreter-wide state changes still affect both programs. For example, if one program imports a module, the other one can see it in sys.modules ; if one program changes a setting in a module, the other one is affected. Locale settings come to mind. Most well designed modules will be fine, but you'll run into the odd one that thinks that module-wide globals are a good idea and consequently chokes.
Unfortunately, the alternative is to use sub-interpreters. Sub-interpreters are a less than well documented part of Python's API, and as they rely on thread local storage they're hopeless in single threaded programs. They can be made to work (see Scribus, for example) but it's not overly safe, and will abort if you use a Python debug build.
When you combine this with a GUI toolkit like Qt3 that only permits GUI operations from the main thread (thankfully, the limitiation is relieved by Qt4), this becomes very frustrating. If you're not stuck with this limitation, you can just spawn off a thread for your users' scripts, and should consider designing your interface that way right from the start.
Embedding Python is handy. Have fun.
P.S: LJ staff, please fix your comment engine's braindeath about leading whitespace, < and > chars in <code> sections, and blank lines in <code> sections. Thankyou. Repeated entities are not a fun way to format text.
--
Craig Ringer
craig@postnewspapers.com.au