在 Qt 的 Project 中添加一個 py 文件。
?
然后在 test_py.py 中的內容如下:
# This Python file uses the following encoding: utf-8 # if__name__ == "__main__": # pass def hello(): print("hello world!")
只有一個 hello()函數,Qt 就是調用這個 hello 函數,然后執行,顯示 hello,world!
在上一節的主文件中添加如下代碼:
PyRun_SimpleString("import sys\n"); PyRun_SimpleString("print(sys.path.append('/Users/wangxinnian/Downloads/qtApp/testQP1'))\n"); PyObject* pModule = PyImport_ImportModule("test_py"); if (!pModule){ printf("不能打開 python file\n"); Py_Finalize(); return -1; } else printf("python文件已經打開了!"); PyObject* pFunHello = PyObject_GetAttrString(pModule, "hello"); // 這里的 hellow 就是 python 文件定義的。 if (!pFunHello){ cout << "Get function hello failed !" <
代碼分析 :
1。 引入了 python 的語句:
import sys
sys.path.append("/Users/wangxinnian/Downloads/qtApp/testQP1")
設置 test_py 尋找的資源路徑,這個就是項目的目錄。
2.使用PyImport_ImportModule
使用該函數打開 py 文件,取得該文件中的模塊函數
3. 找到 hello 函數
使用 PyObject_GeAttrString 查找到模塊中指定的函數
4. 然后執行這個函數
PyObject_CallFunction(pFunHello,nullptr);
運行結果如下:
今日是: Thu Jul 25 10:04:03 2019
大家好!
None
hello world!
python文件已經打開了!hello 模塊已經打開了,開始執行
完整的 main.cpp 內容如下:
#define PY_SSIZE_T_CLEAN #include#include #include using namespace std; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); wchar_t *program = Py_DecodeLocale(argv[0], nullptr); if (program == nullptr) { fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); exit(1); } Py_SetProgramName(program); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString ("from time import time,ctime\n" "print('今日是:', ctime(time()))\n" "print('大家好!')\n" ); PyRun_SimpleString("import sys\n"); PyRun_SimpleString("print(sys.path.append('/Users/wangxinnian/Downloads/qtApp/testQP1'))\n"); PyObject* pModule = PyImport_ImportModule("test_py"); if (!pModule){ printf("不能打開 python file\n"); Py_Finalize(); return -1; } else printf("python文件已經打開了!"); PyObject* pFunHello = PyObject_GetAttrString(pModule, "hello"); // 這里的 hellow 就是 python 文件定義的。 if (!pFunHello){ cout << "Get function hello failed !" <
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
