< BACKMake Note | BookmarkCONTINUE >
152015024128143245168232148039199167010047123209178152124239215162147034164216207026027225

Embedding

We will now talk about how to embed Python inside other programs. Python offers a clean interface that allows embedding to occur.

You might be asking yourself why would you want to do it. Well, the answer is quite simple; as a scripting language, Python can wire its interpreter into other programs to enable you to make calls to specific Python functions and execute particular Python statements from them.

Those programs will have the capability to load Python scripts and execute Python services that belong to specific Python modules. You can also call Python functions directly from your C code and access the Python objects that are returned by them.

In order to embed Python inside a program, you just need to use the Python API—the Python EXE is not necessary.

Implementing Callback Functions

Embedding Python allows you to access and use the Python interpreter from inside your application. But what happens if you need to call back your application functions from inside Python?

For this reason, it is a good practice to provide a module written in C that exposes an API related to the application. Therefore, when embedding Python within your routines, you can make your application communicate both ways with your Python program by accessing the Python extension modules.

Embedding the Python Interpreter

The next example adds Python functionality to a C program.

						
// File: embedding.c

#include <stdio.h>
#include <Python.h>
int main(int argc, char **argv)
{
  Py_Initialize();
  PyRun_SimpleString("print 'Hello Python World'");
  printf("You are my visitor number %i", args);
  Py_Finalize();
  return(0);
}

					

Python provides a set of function calls that provide an interface to the Python interpreter. The most important ones are

  • Py_Initialize—  Initializes and allocates the internal resources of the interpreter in order to start using the API.

  • PyRun_SimpleString—  Executes Python code strings in the context of the __main__ module. Each string must be a complete Python command. This high-level function reads from a character buffer and returns 0 for success and -1 when exceptions occur. Another function called PyRun_String provides more control of the code execution. The source code of this function is available in your installation in the Python/pythonrun.c file.

Tip

Remember that you need to inform the new line character at the end of each command line to make sure that the interpreter validates the command.



Py_Finalize—  Releases the internal resources and shuts down the interpreter. You should always call this function before leaving the program.

PyRun_SimpleFile—  Executes Python commands that are stored in a file. This function reads from a FILE pointer.

Check out this other example:

						
// File: embedding2.c

#include "Python.h"
main(int argc, char **argv)
{
   Py_Initialize();
   PySys_SetArgv(int argc, char **argv);
   PyRun_SimpleString("print 'Hello Python World'\n");
   PyRun_SimpleString("print sys.argv\n");
   PyFinalize();
   Py_Exit(0);
}

					
  • PySys_SetArgv—  This function sets the values for the sys.argv list.

You can access a module written in Python from C by getting a pointer to the module object as follows:

						
module = PyImport_ImportModule("<modulename>");

					

If the module hasn't been imported yet (that is, it isn't yet present in sys.modules), this function initializes the module; otherwise it simply returns the value of sys.modules["<modulename>"].

It doesn't enter the module into any namespace—it only ensures that it has been initialized and it is stored in sys.modules.

You can then access the module's attributes (that is, any name defined in the module) using PyObject_GetAttrString() as follows:

						
attr = PyObject_GetAttrString(module, "<attrname>");

					

It is also possible to assign values to variables in the module using the PyObject_SetAttrString() function.

There is a very straightforward example of embedding Python in a C program in the file /Demo/embed/demo.c, which is part of your Python distribution source code.

Embedding on UNIX

On UNIX, you must link your C application against the Python interpreter library, which is called libpython1.5a.

When compiling the yourprogram.c into a object file (yourprogram.o), you need to specify the directory of the Python distribution.

For example,

							
gcc -g -c yourprogram.c

						

Note

You need to make sure that the header files required by your program are correctly installed on your system.



When compiling the object file into an executable file, you need to include the libraries and references for any extension modules embedded into the Python interpreter itself.

Check the Makefile file of the Python interpreter to know the files that must be mentioned.

							
Listing 6.1  File: Makefile…
VERSION= 1.5

LIBPYTHON= $(blddir)/libpython$(VERSION).a

LIBS= -lreadline -ltermcap -lcurses -lgdbm -ltk8.0 -ltcl8.0 -lX11 -ldl
SYSLIBS= -lm
MODLIBS= -L/usr/X11R6/lib -I/usr/local/pgsql/include
-L/usr/local/pgsql/lib -lcrypt
ALLLIBS= $(LIBPYTHON) $(MODLIBS) $(LIBS) $(SYSLIBS)
…

						

All the libraries found in the Makefile file are used as arguments to the function that compiles the object file, as you can see next.

							
gcc yourprogram.o /usr/local/contrib/Python-1.5.2/libpython1.5.a
-L/usr/X11R6/lib -I/usr/local/pgsql/include -L/usr/local/pgsql/lib
-lcrypt -lreadline -ltermcap -lcurses -lgdbm -ltk8.0 -ltcl8.0 -lX11
-ld1 -lm -o yourprogram

						

The last step is to type make to build the application.

Note

In order to compile an extension module for use with the embedded python interpreter, you just need to compile the module into the executable and make sure that you call the init function for the module after initializing the interpreter.



Embedding Python in C++

You don't have to recompile your interpreter. You just need to write your main program in C++ and use a C++ compiler to compile and link your program.

Embedding Python in Other Applications

On Windows, Python itself is implemented in a DLL called Python15.dll. Note that the file Python.exe is a small program that calls all the routines stored in the DLL. This is a good example showing that it must be easy to embed Python because it already embeds itself.

Besides all this talk about embedding Python in C and C++ applications, Python can also be embedded in other applications, such as Delphi. However, note that implicitly, the embedding process is at the C level too.

Dr. Dietmar Budelsky and Morgan Martinet merged their two separate projects and created The Python for Delphi project. The purpose of this project is to provide an interface to the Python language in Delphi.

This project consists of a set of components that wrap the Python15.dll into Delphi. These components let you easily execute Python scripts, create new Python modules and new Python types. You can create Python extensions as DLLs and much more. Currently, it supports Delphi versions 3, 4, and 5.

The Python for Delphi project:

http://www.multimania.com/marat/delphi/python.htm

NSAPI/NSAPY

A real-life example of how Python can be used by other applications is in the case of embedding Python under Netscape HTTP Servers that support the NSAPI module protocol.

This marriage brings several add-ons to the Netscape Server mostly because of the general scripting capabilities acquired from the Python language.

In order to do this embedding, it is necessary to use the Nsapy, which is an extension that works by embedding the interpreter within Netscape HTTP Servers that use NSAPI.

NSAPI—The Netscape Server API:

http://oradb1.jinr.ru/netscape/NSAPI/

"Nsapy," by Gregory Trubetskoy:

http://www.ispol.com/home/grisha/nsapy/nsapy.html

Example of embedding Python under a Netscape Commerce server:

http://starship.python.net/crew/aaron_watters/embed/


Last updated on 1/30/2002
Python Developer's Handbook, © 2002 Sams Publishing

< BACKMake Note | BookmarkCONTINUE >

Index terms contained in this section

accessing
      module attributes
      modules
applications
     non-Python
            embedding Python objects in 2nd 3rd 4th 5th 6th 7th
assigning
      values to variables, modules
attributes
     modules
            accessing
Budelsky, Dietmar
C programming language
      extending and embedding Python 2nd 3rd 4th 5th 6th 7th
C++ programming language
      extending and embedding Python 2nd 3rd 4th 5th 6th 7th
callback functions
      implementing
compiling
      extension modules
creating
      Python extension modules 2nd 3rd 4th 5th 6th 7th
embedding
      interpreters 2nd 3rd 4th
      Python objects 2nd 3rd 4th 5th 6th 7th
extension modules
      compiling
      creating 2nd 3rd 4th 5th 6th 7th
files
      Makefile
functions
     callback
            implementing
      init()
      PyRun_String()
implementing
      callback functions
init() function
interpreters
      embedding 2nd 3rd 4th
Makefile file
Martinet, Morgan
module attributes
      accessing
module protocols
      NSAPI/NSAPY 2nd
modules
      accessing
     extension
            compiling
            creating 2nd 3rd 4th 5th 6th 7th
      Python15.dll
NSAPI/NSAPY module protocol 2nd
objects
      embedding in non-Python applications 2nd 3rd 4th 5th 6th 7th
programming languages
     C
            extending and embedding Python 2nd 3rd 4th 5th 6th 7th
     C++
            extending and embedding Python 2nd 3rd 4th 5th 6th 7th
programs
     non-Python
            embedding Python objects in 2nd 3rd 4th 5th 6th 7th
protocols
     module
            NSAPI/NSAPY 2nd
PyRun_String() function
Python15.dll module
software
     non-Python
            embedding Python objects in 2nd 3rd 4th 5th 6th 7th
UNIX
      embedding interpreters 2nd
values
      assigning to variables, modules
variables
     modules
            assigning values to

© 2002, O'Reilly & Associates, Inc.