如题,运行时无法读取python文件。编译器是qt的creator,都是32位的。
.pro文件的内容
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
win32: LIBS += -LD:/python3.6.7/libs/ -lpython36
INCLUDEPATH += D:/python3.6.7/libs
DEPENDPATH += D:/python3.6.7/libs
win32:!win32-g++: PRE_TARGETDEPS += D:/python3.6.7/libs/python36.lib
else:win32-g++: PRE_TARGETDEPS += D:/python3.6.7/libs/libpython36.a
main.cpp中的内容
//#include "mainwindow.h"
//#include <QApplication>
# include "D:\python3.6.7\include\Python.h"
# include <iostream>
# include <QtDebug>
int main(int argc, char *argv[])
{
Q_UNUSED(argc)
Q_UNUSED(argv)
// QApplication a(argc, argv);
// MainWindow w;
// w.show();
// return a.exec();
Py_SetPythonHome(L"D:\\python3.6.7");
Py_Initialize(); // 初始化python解释器
// 将python工作路径切换到带调用mo'kuai 所在目录,一定要保证路径名的正确性
// 判断是否成功
if(!Py_IsInitialized()){
qDebug() << "python初始化失败,即将退出程序";
return -1;
}
// 导入测试的py文件
PyObject * pModule = PyImport_ImportModule("test.py");
if(!pModule){
qDebug() << sizeof (* pModule);
qDebug() << "导入python文件失败,即将退出程序";
return -1;
}
// 获取py文件的phello函数。
PyObject * pFun_phello = PyObject_GetAttrString(pModule, "phello");
if(!pFun_phello){
qDebug() << "获得py文件的函数失败,即将退出程序";
}
// 调用phello函数。
PyObject * jiehuo_helloworld = PyObject_CallFunction(pFun_phello, 0);
char * reshelloworld;
PyArg_Parse(jiehuo_helloworld, "s", &reshelloworld);
qDebug() << "我成功的在qt内实现了利用python打印" << reshelloworld;
qDebug() << sizeof(void*)*8;
}
test.py
def phello():
return 'hello world!'
def noadd(a, b):
return a+b
如果注释掉main.cpp中判断py文件是否读取成功那里的代码,会说程序异常结束,倘若不注释掉的话,会打印:
8
导入python文件失败,即将退出程序