Calling a C program from a Python Script

Jeff Shannon jeff at ccvcorp.com
Thu Dec 9 16:08:57 EST 2004


Brad Tilley wrote:

> I just want to know the basics of using C and Python together when the 
> need arises, that's all, I don't want to write a book about what 
> exactly it is that I'm involved in.


Well, there's several different ways of using C and Python together, so 
the only meaningful answer we can give you is "It depends on what you're 
trying to do."

What your pseudocode seems to show would be appropriate for something 
along the lines of os.system(), os.startfile(), or some variant of 
popen().  Any of these will run a free-standing executable program.  But 
they may not be ideal for making data available to Python.

There's ctypes, which will allow you to call functions in a C shared 
library (i.e. a DLL, not sure if it works for *nix .so files).

There's also the possibility of writing Python extensions in C.  This is 
a bit more up-front work, but may make usage easier.  The extension 
(provided it's not buggy) works just like any other Python module. 

SWIG is a tool that automates the wrapping of existing C code into a 
Python extension.  Whether this is a suitable tool for you depends on 
what code you already have, and what responsibilities you're hoping to 
pass from Python code into C code.

And do note that, as others have said, calling C code won't 
*necessarily* make your program work faster.  It's only going to help if 
you're replacing slow Python code with faster C code -- not all Python 
code is slow, and not all C code is fast, and if you're writing C from 
scratch then you want to be sure where the hotspots are and focus on 
converting only those areas to C.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list