Qt混合Python编程基本使用

打算用Qt做一个类似手机日历的Windows程序,使用聚合数据的api,返回json格式数据。尽管Qt可以处理json数据,还是打算调用Python。

pro文件添加以下内容

INCLUDEPATH += "C:\Program Files\Python36\include"

LIBS += "C:\Program Files\Python36\libs\python36.lib"

必须以Release方式编译。

编译时出现

C:\Program Files\Python36\include\object.h:448: error: C2238: 意外的标记位于“;”之前

错误。

Qt混合Python编程基本使用_第1张图片

参考http://www.cnblogs.com/jiaping/p/6321859.html http://www.cnblogs.com/findumars/p/6142330.html

把上述文件改为

Qt混合Python编程基本使用_第2张图片

Extending and Embedding the Python Interpreter — Python 3.6.5 documentation

https://docs.python.org/3.6/extending/index.html

Python/C API Reference Manual — Python 3.6.5 documentation

https://docs.python.org/3.6/c-api/index.html

上面两个链接是详细的官方文档,下面的代码实现调用无参数无返回值、有参数无返回值和无参数有返回值的Python函数。

mytest.py

def hello():
    print("python mytest")

def arg_in(a, b, s):
    print(a + b)
    print(s)

def arg_out():
    return 12, 34, "arg out str"
    Py_Initialize();
    if (!Py_IsInitialized())
    {
        qDebug() << "python is not initialized";
    }
    else
    {
        QString str = "sys.path.append('" + QDir::currentPath() + "')";
        PyRun_SimpleString("import sys");
        PyRun_SimpleString(str.toStdString().c_str());
        PyRun_SimpleString("print(sys.path)");

        PyObject *pModule = PyImport_ImportModule("mytest");
        if (!pModule)
        {
            qDebug() << "can not import python module file";
        }
        else
        {
            PyObject *pFun = PyObject_GetAttrString(pModule, "hello");
            if (!pFun)
            {
                qDebug() << "can not get function";
            }
            else
            {
                PyObject_CallFunction(pFun, nullptr);
            }

            PyObject *pFun2 = PyObject_GetAttrString(pModule, "arg_in");
            if (!pFun2)
            {
                qDebug() << "can not get function";
            }
            else
            {
                //PyObject* args = Py_BuildValue("(ifs)", 100, 3.14, "arg in str");
                PyObject *args = PyTuple_New(3);
                PyObject* arg = Py_BuildValue("i", 100);
                PyObject* arg2 = Py_BuildValue("f", 3.14);
                PyObject* arg3 = Py_BuildValue("s", "arg in str");
                PyTuple_SetItem(args, 0, arg);
                PyTuple_SetItem(args, 1, arg2);
                PyTuple_SetItem(args, 2, arg3);

                PyObject_CallObject(pFun2, args);
            }

            PyObject *pFun3 = PyObject_GetAttrString(pModule, "arg_out");
            if (!pFun3)
            {
                qDebug() << "can not get function";
            }
            else
            {
                PyObject* pRet = PyObject_CallObject(pFun3, Py_BuildValue("()"));
                int a;
                int b;
                char *s;
                PyArg_ParseTuple(pRet, "iis", &a, &b, &s);
                qDebug() << a << b << s;
            }
        }
    }
    Py_Finalize();

你可能感兴趣的:(Qt)