C语言中调用运行python程序

时间:2023-03-08 19:22:24
C语言中调用运行python程序

C语言中调用运行python程序:

Python代码如下:

创建test.py。

#!/usr/bin/python3
#test.py
import sys
x = int(sys.argv[])
print x*x

注意:(#!/usr/bin/python3这一行代码要根据自己的硬件情况而定)

C语言代码如下:

创建test.c。

//test.c
#include <stdio.h>
#include <stdlib.h> int main()
{
FILE *f;
char s[];
int ret; f = popen("./test.py 99", "r");
while((ret=fread(s,,,f))>) {
fwrite(s,,ret,stdout);
}
fclose(f);
return ;
}

测试如下:

$ gcc -o test test.c
$ ./test