关闭

C++、Qt内嵌python

标签: qtpythonc++
381人阅读 评论(0) 收藏 举报
分类:

C++内嵌python

python重要的路径:

/usr/local/include/python3.6m
/usr/local/bin/python3-config
/usr/local/bin/python3.6
/usr/local/bin/python3
/usr/local/bin/python3.6-config
/usr/local/bin/python3.6m
/usr/local/bin/python3.6m-config
/usr/local/lib/python3.6
/usr/local/lib/python3.6/site-packages/numpy/lib/tests/data/python3.npy
/usr/local/lib/pkgconfig/python3.pc
/usr/local/share/man/man1/python3.1
/usr/local/share/man/man1/python3.6.1
/usr/share/vim/vim74/autoload/python3complete.vim
/usr/share/doc/python-setuptools-0.6.10/docs/python3.txt
/usr/share/doc/python-setuptools-0.6.10/docs/build/html/_sources/python3.txt

在文件/usr/local/lib/pkgconfig/python-3.6.pc中给出了引用头文件和连接库文件的信息:

# See: man pkg-config
prefix=/usr/local
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include

Name: Python
Description: Python library
Requires: 
Version: 3.6 
Libs.private: -lpthread -ldl  -lutil -lrt
Libs: -L${libdir} -lpython3.6m
Cflags: -I${includedir}/python3.6m

include路径包含了各种头文件:/usr/local/include/python3.6m
库文件目录为:/usr/local/lib 静态库文件是libpython3.6m.a
C/C++中内嵌python的文章:http://python.usyiyi.cn/translate/python_352/c-api/intro.html#embedding-python

简单python引用

需要引用的py代码,pytest.py :

def show():
    print("hello world!")

C++代码,test.cpp

#include "Python.h"
#include <iostream>
using namespace std;

int main(int argc,char **argv){
    Py_Initialize();
    PyRun_SimpleString("import sys"); 
    PyRun_SimpleString("sys.path.append('/home/edemon/workspace/qt_cpp/untitled/tmp')");
    // import py file.
    PyObject* pModule = PyImport_ImportModule("pytest");
    if(pModule == NULL){
        cout<<"my test py file open failed.";
        return -1; 
    }  
    // import function
    PyObject* pyFun = PyObject_GetAttrString(pModule,"show");
    if(pyFun == NULL){
        cout<<"pyFun get failed.";
        return -1; 
    }  
    // call function
    PyObject_CallFunction(pyFun,NULL);
    Py_Finalize();
    return 0;
}

使用g++编译:g++ test.cpp -I /usr/local/include/python3.6m -L/usr/local/lib -lpython3.6m -lrt -ldl -lutil -o test

C++内嵌导入其他模块的python

下面的程序是利用python安装的tushare模块请求顺丰控股的价位峰值数据

import tushare

def data_high():
    print(tushare.get_hist_data(code='002352',start='2016-09-01',end='2016-09-20').high)
def data_low():
    print(tushare.get_hist_data(code='002352',start='2016-09-01',end='2016-09-20').low)

在C++中引用相关的函数:

#include "Python.h"
#include <iostream>
using namespace std;

int main(int argc,char **argv){
    Py_Initialize();
    PyRun_SimpleString("import sys"); 
    PyRun_SimpleString("sys.path.append('/home/edemon/workspace/qt_cpp/untitled/tmp/advanced')");
    //PyRun_SimpleString("sys.path.append('/usr/local/lib/python3.6/site-packages/tushare')");

    PyObject* pModule = PyImport_ImportModule("myData");
    if(pModule == NULL){
        cout<<"my test py file open failed.";
        return -1; 
    }  
    PyObject* pDataHigh = PyObject_GetAttrString(pModule,"data_high");
    if(pDataHigh == NULL){
        cout<<"data_high get failed.";
        return -1; 
    }  
    PyObject_CallFunction(pDataHigh,NULL);
    Py_Finalize();
    return 0;
}

运行:

$  g++ main.cpp -I /usr/local/include/python3.6m -L/usr/local/lib -lpython3.6m -lrt -ldl -lutil  -Xlinker -export-dynamic -o main
$ ./main
date
2016-09-20    45.52
2016-09-19    42.39
2016-09-14    40.80
2016-09-13    39.70
2016-09-12    39.87
2016-09-09    40.00
2016-09-08    38.99
2016-09-07    39.40
2016-09-06    39.12
2016-09-05    39.27
2016-09-02    40.49
2016-09-01    40.36
Name: high, dtype: float64

注意加上:-Xlinker -export-dynamic,动态链接库文件。

QT内嵌python

在工程文件pro中注意includepath和libs的设置:

# add extra info for qt
INCLUDEPATH += "/usr/local/include/python3.6m"
LIBS += "-L/usr/local/lib" -lpython3.6m -lrt -ldl -lutil -Xlinker -export-dynamic

和C++内嵌python的例子类似,这里将得到的峰值数据写入文件中。
data.py:

#! /usr/local/bin/python3
import os
import tushare

def data_high():
    res = tushare.get_hist_data(code='002352',start='2016-09-01',end='2016-09-20').high
    os.chdir("./")
    res_file = open("result.txt","w")
    print(res,file=res_file)      
    res_file.close()

def data_low():
    return ts.get_hist_data(code='002352',start='2016-09-01',end='2016-09-20').low

main.cpp:

#include "Python.h"
#include <QApplication>
#include <QDebug>

int main(int argc,char **argv){
    QApplication app(argc,argv);
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyObject* pModule = PyImport_ImportModule("data");
    if(pModule == NULL){
        qDebug()<<"data.py can't open failed.";
        return -1;
    }
    PyObject* pDataHigh = PyObject_GetAttrString(pModule,"data_high");
    if(pDataHigh == NULL){
        qDebug()<<"data_high get failed.";
        return -1;
    }
    PyObject_CallFunction(pDataHigh,NULL);
    Py_Finalize();
    return app.exec();
}

你可能在make的时候会遇到类似于这样的问题:

n file included from /usr/local/include/python3.6m/pytime.h:6:0,
                from /usr/local/include/python3.6m/Python.h:65,
                from main.cpp:2:
/usr/local/include/python3.6m/object.h:448:20: error: expected unqualified-id before ‘;’ token
  PyType_Slot *slots;  /* terminated by slot==0. */
                    ^

这是因为slots是qt的关键字,故在引用头文件的时候需先引用python,即#include "Python.h" 不能在#include <QApplication> 的后面。像这样:

#include <QApplication>
#include "Python.h"
#include <QDebug>

修改pro文件后,及时更新Makefile: qmake -makefile,然后再make即可。

0
0
查看评论
发表评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场

译;将Python嵌入到Qt程序中

翻译Qt Quarterly的一篇文章: 利用PythonQt将Python嵌入到Qt程序中
  • jingwenlai_scut
  • jingwenlai_scut
  • 2010-06-02 15:03
  • 9424

Qt调用Python脚本

因为Python库比较强大,所以就采用Qt去调用Python脚本进行项目开发,下面是Qt调用Python脚本,结合CPython进行传值等 使用的编译器是QtCreater5.6 使用Python...
  • yinyuchen1
  • yinyuchen1
  • 2017-09-01 17:53
  • 835

QT C++中直接调用python接口

本文记录在Qt中直接调用python接口的方式 python文件,testList.pyt如下: #!/usr/bin/python def testlist():   a = ['tomsun', ...
  • xiranchen
  • xiranchen
  • 2014-12-10 11:02
  • 4746

QT/C++ 下调用python自定义模块

QT5.6 Python2.7 QT/C++调用python比较麻烦。C++想要调用python,先要包含头文件。第一步需要添加python的头文件路径。在QT项目的.pro文件下添加这两句 INCL...
  • Simon0o
  • Simon0o
  • 2016-11-13 12:16
  • 2329

c++调用python脚本遇到的那些坑

问题一:一开始我是在qt上编写程序的,qt是32bit,但Python是64bit,在*.pro文件中配置了: INCLUDEPATH += C:/Python27/include/ LIBS +=...
  • JR_lu
  • JR_lu
  • 2017-01-06 21:41
  • 2985

Python中使用Mysql(安装篇)

准备工作 import MySQLdb Linux系统自带了Python,但并不是都有这个包,至少我每次拿到一台全新的服务器时候,都发现没有装这个包。 这个东西的下载地址是 http://sou...
  • u012063703
  • u012063703
  • 2014-11-08 18:07
  • 6449

手动安装postgis时遇到的坑

在使用源代码安装postgis的过程中, 需要先安装proj-4.9.1,geos-3.5.0,libxml2-2.6.30, 最后再安装postgis. 以下是安装过程中遇到的坑.
  • u011170540
  • u011170540
  • 2016-08-19 11:19
  • 2242

Linux安装vsftp:install: 无法创建普通文件“/usr/local/man/man8/vsftpd.8”:没有那个文件或目录

在编译模式中安装vsftpd时,出错:install:无法创建普通文件“/usr/local/man/man8/vsftpd.8”:没有那个文件或目录  如下图 找到安装的目录,修改安装的配置文件M...
  • xiaokui_wingfly
  • xiaokui_wingfly
  • 2015-05-09 22:40
  • 2528

C++ 内嵌 python 例程

#include int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pDict, *pFunc; //所有针对p...
  • akinosun
  • akinosun
  • 2012-03-06 17:37
  • 341

脚本系统:c++内嵌python

// liquidx.cpp : Defines the entry point for the console application.// #include "stdafx.h" #include...
  • liqunzheng
  • liqunzheng
  • 2013-03-11 18:07
  • 366
    个人资料
    • 访问:327277次
    • 积分:8806
    • 等级:
    • 排名:第2521名
    • 原创:574篇
    • 转载:13篇
    • 译文:0篇
    • 评论:36条
    我的链接
    最新评论