Using C to execute Python

Michael P. Reilly arcege at shore.net
Wed Jun 23 07:23:44 EDT 1999


In comp.lang.python Thomas R.berg <thomar at ifi.ntnu.no> wrote:
: I have a C program and I want to call certain Python methods / functions
: passing quite a few parameters.
: How can I do this, in general fashion?
: I would have to include python.h, I reckon - where can I find this, I've
: been searching all over for it (is it just me???)
: I'm no expert, far from, in Python...

: Thomas
: email: thomar at ifi.ntnu.no

Hi Thomas,

You will need the full source distribution of Python (the default Linux
distribution, the binary distributions come with the header files, etc.).

Compile and install that.  Then read "Extending and Embedding the
Python Interpreter" (http://www.python.org/doc/current/ext/ext.html)
and "Python/C API Reference Manual"
(http://www.python.org/doc/current/api/api.html) to describe how to
embed Python.

Very simply,
  1) Initialize Python (with Py_Initialize())
  2) Run some of the Python API calls (high-level or low-level)
  3) When you are done, call Py_Finalize()

int callpython(python_cmd)
  char *python_cmd;
  { int rc;

    if (!Py_IsInitialized())
      Py_Initialize();
    rc = PyRun_SimpleString(python_cmd);
    return rc;
  }

The problem with this is that exceptions are not captured and are
printed to stderr directly.  The lower-level API calls give finer
control, but luckily very easy to code (compared to other P*
languages).

  -Arcege





More information about the Python-list mailing list