本文记录如何在C语言中嵌入python代码并编译运行的步骤,及编译时遇到的一些问题。
1、环境准备
即下载安装python和gcc。
我的版本是
- python 3.9.12 64位
- gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)
这个自己找网上下载安装,不多赘述,安装时记得把添加到环境变量勾选上,或自己把安装好的路径手动添加到环境变量path中。
切记python的版本和gcc的版本结构必须是一样的,比如python32位,对应使用gcc32位。
2、创建代码
直接上例子,创建一个read_file.c文件,加入代码:
#include <Python.h>
int main() {
// 初始化Python解释器
Py_Initialize();
// 执行Python代码
PyRun_SimpleString(
"file = open('example.txt', 'r')\n"
"content = file.read()\n"
"file.close()\n"
"if 'key' in content:\n"
" print('File contains the keyword')\n"
"else:\n"
" print('File does not contain the keyword')"
);
// 清理Python解释器
Py_Finalize();
system("pause");
return 0;
}
3、编译
输入以下命令编译:
gcc example.c -o example -Ipath/python/include -Lpath/python/libs -lpythonxx
-o 指定输出程序
-I 指定python头文件地址
-L 指定python库路径
-l 指定引用的python库
下面是我环境的例子,具体根据自己环境修改对应的路径和python版本:
# powershell下
cd "D:\Program Files\mingw\mingw64\bin\gcc.exe"
.\gcc.exe E:\Gitee\PythonProjects\Python\cpython\read_file.c -o E:\Gitee\PythonProjects\Python\cpython\read_file "-ID:\Program Files\Python39\include" "-LD:\Program Files\Python39\libs" -lpython39
# 或者
# 命令行下
"D:\Program Files\mingw\mingw64\bin\gcc.exe" read_file.c -o read_file "-ID:\Program Files\Python39\include" "-LD:\Program Files\Python39\libs" -lpython39
4、可能遇到的问题
列举几个我遇到的问题:
- 找不到头文件error: Files\Python39\include: No such file or directory
–> 路径包含空格,需要加引号。
"-ID:\Program Files\Python39\include"
- 编译时提示python接口未定义undefined reference to `_imp__Py_Initialize’
d:/program files/mingw-w64-gcc-11.3-stable-r37/bin/../lib/gcc/i686-w64-mingw32/11.3.0/../../../../i686-w64-mingw32/bin/ld.exe: C:\Users\HYSYB-~1\AppData\Local\Temp\cczpLgNh.o:read_file.c:(.text+0xf): undefined reference to `_imp__Py_Initialize'
–> 是因为我电脑同时存在32和64位的gcc,我python用的是64位,编译也需要用gcc 64位。
- 指定gcc版本
不同命令行下的处理有点不一样:
powershell下
# 先切换再执行
cd "D:\Program Files\mingw\mingw64\bin\gcc.exe"
.\gcc.exe -v
# 或者定义一个函数,再调用函数执行
function gcc64 {& "D:\Program Files\mingw\mingw64\bin\gcc.exe" $args}
gcc64 -v
命令行下
# 直接调用执行
"D:\Program Files\mingw\mingw64\bin\gcc.exe" -v
# 或者创建别名,然后用别名调用,如果希望每次启动命令行都自动加载这个别名,可以将命令添加到用户或系统的启动脚本中。
doskey gcc64="D:\Program Files\mingw\mingw64\bin\gcc.exe" $*
gcc64 -v
5、运行
直接运行:
./read_file.exe
File does not contain the keyword
# 如果要读的文件不存在:
Traceback (most recent call last):
File "<string>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'
也可以直接双击。