C语言中调用运行python程序

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

Python代码如下:

创建test.py。

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

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

C语言代码如下:

创建test.c。

//test.c
#include <stdio.h>
#include <stdlib.h>

int main()
{
        FILE *f;
        char s[10240];
        int ret;

        f = popen("./test.py 99", "r");
        while((ret=fread(s,1,1024,f))>0) {
                fwrite(s,1,ret,stdout);
        }
        fclose(f);
        return 0;
}

测试如下:

$ gcc -o test test.c
$ ./test
9801
posted @ 2019-11-13 22:06  小大大小  阅读(2867)  评论(0编辑  收藏  举报