简体   繁体   English

如何使用嵌入式python脚本编译和运行C代码?

[英]how to compile and run C code with embedded python script?

I am using this example from python documentation 我正在使用python文档中的示例

#include <Python.h>
int
main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print('Today is', ctime(time()))\n");
  Py_Finalize();
  return 0;
}

where python script is hard-coded to a C program. python脚本被硬编码到C程序中。 But when i try to compile it by 但是当我尝试通过编译它时

$ gcc -c modwithpy.c -o mod

i receive an error: 我收到一个错误:

modwithpy.c:1:20: fatal error: Python.h: No such file or directory compilation terminated. modwithpy.c:1:20:致命错误:Python.h:没有终止此类文件或目录的编译。

however, i have already install python-dev package. 但是,我已经安装了python-dev软件包。 I also looked at compiling and linking documentation and don't understand what absolute path for python package i need to write. 我也查看了编译和链接文档 ,但不了解我需要为python包写什么绝对路径。

$ whereis python
python: /usr/bin/python3.3m /usr/bin/python /usr/bin/python2.7-config 
/usr/bin/python3.3 /usr/bin/python2.7 /etc/python /etc/python3.3 /etc/python2.7
/usr/lib/python2.6 /usr/lib/python3.3 /usr/lib/python2.7 /usr/bin/X11/python3.3m
/usr/bin/X11/python /usr/bin/X11/python2.7-config /usr/bin/X11/python3.3
/usr/bin/X11/python2.7 /usr/local/lib/python3.3 /usr/local/lib/python2.7
/usr/include/python2.7 /usr/share/python /usr/share/man/man1/python.1.gz

You didn't read quite far enough. 您读得还不够远。 The documentation here shows how to tell the compiler where python headers and libraries are located. 此处的文档显示了如何告诉编译器python标头和库的位置。

Based on this, try 基于此,尝试

gcc `/opt/bin/python3.3-config --cflags` modwithpy.c -o mod \
  `/opt/bin/python3.3-config --ldlags`

If your python installed scripts in a different place, you will have to change the /opt/bin to the place where ...-config is really located. 如果您的python安装脚本位于其他位置,则必须将/opt/bin更改为...-config的实际位置。 From your whereis trace, it could be /usr/bin . 在您的whereis跟踪中,它可能是/usr/bin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM