Basic Embedding Techniques

As you can probably tell from the preceding overview, there is much flexibility in the embedding domain. To illustrate common embedding techniques in action, this section presents a handful of short C programs that run Python code in one form or another. Most of these examples make use of the simple Python module file shown in Example 23-1.

Example 23-1. PP3E\Integrate\Embed\Basics\usermod.py

#########################################################
# C runs Python code in this module in embedded mode.
# Such a file can be changed without changing the C layer.
# There is just standard Python code (C does conversions).
# You can also run code in standard modules like string.
#########################################################

message = 'The meaning of life...'

def transform(input):
    input = input.replace('life', 'Python')
    return input.upper( )

If you know any Python at all, you probably know that this file defines a string and a function; the function returns whatever it is passed with string substitution and uppercase conversions applied. It’s easy to use from Python:

.../PP3E/Integrate/Embed/Basics$python
>>> import usermod                                      # import a module
>>> usermod.message                                     # fetch a string
'The meaning of life...'
>>> usermod.transform(usermod.message)                  # call a function
'THE MEANING OF PYTHON...'

With a little Python API wizardry, it’s not much more difficult to use this module the same way in C.

Running Simple Code Strings

Perhaps the simplest way to run Python code ...

Get Programming Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.