环境:Fedora12 + Python2.6 + C
1. 建立python源代码文件(del.py):
#!/usr/bin/env python def calculate(expression): try: result = eval(expression) except: print("Eval Error!") return None return result if __name__ == "__main__": f = open("aa.log", "w") f.write("Hello world ") f.close() print("what can I do for you") expression = "2^(4+2)" result = calculate(expression) print(result)
/* 功能:C程序中执行python代码或python源程序文件 */ #include <Python.h> int main() { int n = 0; char fname[] = "del.py"; FILE *fp = fopen(fname, "r"); // 打开python源码文件 if(fp == NULL) { perror("fopen"); return 1; } Py_Initialize(); // 初始化python解释器 n = PyRun_SimpleString("print(eval(2*6))"); // 执行python代码 printf("1. n = %d ", n); n = PyRun_SimpleFile(fp, fname); // 执行python文件 printf("2. n = %d ", n); Py_Finalize(); fclose(fp); return 0; }
CC=gcc CFLAGS=-g BIN=a $(BIN): $(BIN).c $(CC) $(CFLAGS) -o $(BIN) $(BIN).c -I/usr/include/python2.6 -lpython2.6 clean: rm -f *.o $(BIN)
[zcm@t #87]$ls a.c del.py makefile socket [zcm@t #88]$make gcc -g -o a a.c -I/usr/include/python2.6 -lpython2.6 [zcm@t #89]$./a 1. n = 0 what can I do for you 2. n = 0 [zcm@t #90]$ls a aa.log a.c del.py makefile socket [zcm@t #91]$cat aa.log Hello world [zcm@t #92]$