环境:Fedora12 + Python2.6 + C
1. 建立python源代码文件(del.py):
#!/usr/bin/env pythondef calculate(expression):try:result = eval(expression)except:print("Eval Error!")return Nonereturn resultif __name__ == "__main__":f = open("aa.log", "w")f.write("Hello world\n")f.close()print("what can I do for you")expression = "2^(4+2)"result = calculate(expression)print(result)
2. 建立C源程序(a.c):
/*功能: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", n);n = PyRun_SimpleFile(fp, fname); // 执行python文件printf("2. n = %d\n\n", n);Py_Finalize();fclose(fp);return 0;
}
3. 编写makefile文件
CC=gcc
CFLAGS=-g
BIN=a$(BIN): $(BIN).c$(CC) $(CFLAGS) -o $(BIN) $(BIN).c -I/usr/include/python2.6 -lpython2.6clean:rm -f *.o $(BIN)
4. 编译运行
[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
12
1. n = 0what can I do for you
4
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]$
说明:这个代码演示的是python代码高级嵌入方式!