Extending and Embedding the Python Interpreter

Posted by Anonymous 0 komentar
Python is an interpreted, object-oriented programming language. This document describes how to write modules in C or C++ to extend the Python interpreter with new modules. Those modules can define new functions but also new object types and their methods. The document also describes how to embed the Python interpreter in another application, for use as an extension language. Finally, it shows how to compile and link extension modules so that they can be loaded dynamically (at run time) into the interpreter, if the underlying operating system supports this feature. This document assumes basic knowledge about Python. For an informal introduction to the language, see the Python Tutorial. The Python Reference Manual gives a more formal definition of the language. The Python Library Reference documents the existing object types, functions and modules (both built-in and written in Python) that give the language its wide application range. For a detailed description of the whole Python/C API, see the separate Python/C API Reference Manual.

It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can’t be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls. To support extensions, the Python API (Application Programmers Interface) defines a set of functions, macros and variables that provide access to most aspects of the Python run-time system. The Python API is incorporated in a C source file by including the header "Python.h". The compilation of an extension module depends on its intended use as well as on your system setup; details are given in later chapters.

Let’s create an extension module called ‘spam’ (the favorite food of Monty Python fans...) and let’s say we want to create a Python interface to the C library function system().1 This function takes a null-terminated character string as argument and returns an integer. We want this function to be callable from Python as follows: >>> import spam >>> status = spam.system("ls -l") Begin by creating a file ‘spammodule.c’. (Historically, if a module is called ‘spam’, the C file containing its implementation is called ‘spammodule.c’; if the module name is very long, like ‘spammify’, the module name can be just ‘spammify.c’.) The first line of our file can be: #include Download free Extending and Embedding the Python Interpreter here

0 komentar:

Post a Comment