52

Windows 嵌入python解释器

 4 years ago
source link: https://www.tuicool.com/articles/qaqErym
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

这次主要记录在windows下嵌入 python 解释器的过程,程序没有多少,主要是头文件与库文件的提取。

程序平台:windows10 64 bit、 Qt 5.5.1  MSVC  2013 32 bit  python 3.7.4  32 bit

在ubuntu和 windows 下使用 C/C++ 嵌入 Python 是有些不同的, ubuntu 下可以使用对应命令来获取 python 配置信息, windows 下直接链接对应库文件与头文件即可。

通过对python解释器的嵌入,我们可以自己做一个 python 编辑器,在内部可以定义自己的包;在运行时候 python 脚本的编写就相当于一个随时可变而又无需编译的动态库了。当然,有点还有很多,这种 C/C++ 嵌入脚本语言的应用在游戏上也十分常用。好了,下面简单说下嵌入的流程。

1. Python 安装包下载

我是直接在官网上下载的,Downloads-->>Python3.7.4。

ZrEJv2j.jpg!web

2.  提取库文件与头文件

安装完的文件如下图,其中 include 文件夹里面是头文件, python37.dll 是我们所需要的动态链接库,就像 linux 下的 .so 文件一样。

6ZrmEzY.png!web

3. 在Qt下嵌入 python

我使用的是Qt的控制台程序,也就是 C++ 嵌入 python

pro 文件中链接库

Qt pro中文件如图:

注意:虽然系统是64位的,但是 Qtpython 都是 32 位的

In2eUvv.png!web

②在 C++ 程序中调用 python

在程序中调用python语句分以下几个步骤

1> 包含头文件

2> 初始化python解释器

3> 使用C接口运行 python 语句

4> 调用完成后释放资源。当然也可以再构造函数中初始化一次,在析构函数中再释放资源。

MjYfquy.png!web

4.  程序运行结果

6JvERzu.png!web

最后再说些其他的:在嵌入python中有以下几个问题要考虑:

python 脚本的静态语法检查与运行中错误的输出

python 输出信息重定向到宿主程序

③如何停止、暂停 ( 钩子函数 ) 正在运行的 python 脚本

④当运行 python 阻塞接口时,停止会怎样?

python 脚本中有耗时操作,需要运行到线程或进程中

愿大家:

拥有梦想、实现价值

我是大贺,欢迎大家一起交流!

eIZJ3iQ.jpg!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK