Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a C program in python?

Tags:

python

c

I have this C program, at least I think it is (files: spa.c, spa.h). Is there any way I can execute this script from Python WITHOUT passing extra arguments to the Python interpreter (if not, what would the arguments be?)

Update: Thanks for your replies. The source code can be found at http://www.nrel.gov/midc/spa/#register

(Please do not be scared by the 'register' in the url, if you fill in the form, you can immediately download the files (no validation mails, etc) I will try your suggestions and report back with the results.

Update 2: I compiled the source code using gcc, but now it gives me a permission denied when trying to call(), even when running python as root (im on Ubuntu 10:10).

Update 3 [Errno 8] Exec format error

Update 4 Ok, I got it working. Program outputs values using printf:

>>> call(['/path'])
Julian Day:    2452930.312847
L:             2.401826e+01 degrees
B:             -1.011219e-04 degrees
R:             0.996542 AU
H:             11.105902 degrees
Delta Psi:     -3.998404e-03 degrees
Delta Epsilon: 1.666568e-03 degrees
Epsilon:       23.440465 degrees
Zenith:        50.111622 degrees
Azimuth:       194.340241 degrees
Incidence:     25.187000 degrees
Sunrise:       06:12:43 Local Time
Sunset:        17:20:19 Local Time

Thanks all!

like image 712
Izz ad-Din Ruhulessin Avatar asked Dec 07 '10 12:12

Izz ad-Din Ruhulessin


3 Answers

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"])
like image 55
Pablo Santa Cruz Avatar answered Oct 30 '22 23:10

Pablo Santa Cruz


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)
like image 30
John La Rooy Avatar answered Oct 31 '22 01:10

John La Rooy


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.

like image 43
Lou Franco Avatar answered Oct 30 '22 23:10

Lou Franco