|
|
|
Extending and Embedding the Python Interpreter |
|
|
|
5.1 Very High Level Embedding
The simplest form of embedding Python is the use of the very
high level interface. This interface is intended to execute a
Python script without needing to interact with the application
directly. This can for example be used to perform some operation
on a file.
#include <Python.h>
int
main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}
The above code first initializes the Python interpreter with
Py_Initialize(), followed by the execution of a hard-coded
Python script that print the date and time. Afterwards, the
Py_Finalize() call shuts the interpreter down, followed by
the end of the program. In a real program, you may want to get the
Python script from another source, perhaps a text-editor routine, a
file, or a database. Getting the Python code from a file can better
be done by using the PyRun_SimpleFile() function, which
saves you the trouble of allocating memory space and loading the file
contents.
Release 2.5.2, documentation updated on 21st February, 2008.
See About this document... for information on suggesting changes.
|