Executing a C program in python?

C is not a scripting language. You have to compile spa.c into an executable. You don't say your OS, but if Mac or Linux, try

  gcc spa.c -o spa

If that works, you now have a executable named spa. You can use python's os.system() to call it.


There is no such thing as a C script. If you meant a C program you need to compile spa.c and spa.h into an executable before running it.

If you use GCC in Linux or Mac OS X:

$ gcc -Wall spa.c -o spa

Will get you an executable named spa.

After that, you can run spa program from your Python script with:

from subprocess import call
call(["./spa", "args", "to", "spa"])

cinpy comes close using the awesome combination of tcc and ctypes

The following code is ripped from cinpy_test.py included in the package.

import ctypes
import cinpy

# Fibonacci in Python
def fibpy(x):
    if x<=1: return 1
    return fibpy(x-1)+fibpy(x-2)

# Fibonacci in C
fibc=cinpy.defc("fib",
                ctypes.CFUNCTYPE(ctypes.c_long,ctypes.c_int),
                """
                long fib(int x) {
                    if (x<=1) return 1;
                    return fib(x-1)+fib(x-2);
                }
                """)

# ...and then just use them...
# (there _is_ a difference in the performance)
print fibpy(30)
print fibc(30)

Tags:

Python

C