Wednesday, 26 November 2008

HOWTO: Calling c (or other programs) from python

Calling c (or other programs) from python

1. swig (to generate a python extention from c)
2. dl, python object (to call c shared library)
3. os.popen() (to call other exetuable programs)

In this example, I will use the 3rd method.

1) c program.
This is an example from netbeans, it can print all the arguments, argv[0] is the program name.
# args.c ###################################
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char**argv) {
int i;
// Prints arguments
printf("Arguments:\n");
for (i = 0; i < argc; i++) {
printf("%i: %s\n", i, argv[i]);
}

return 0;
}
#############################
compile it:
####
gcc args.c -o a.out
####

2) python script

# in python script ################
import os
printed = os.popen('./a.o hello world')
>>> printed.readline()
'Arguments:\n'
>>> printed.readline()
'0: ./a.o\n'
>>> printed.readline()
'1: hello\n'
>>> printed.readline()
'2: world\n'
>>> printed.readline()
''
##################################
Here printed is an python array object, all the methods for array are available.

No comments:

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter