Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从cpp获取python函数的打印_Python_C++ - Fatal编程技术网

如何从cpp获取python函数的打印

如何从cpp获取python函数的打印,python,c++,Python,C++,我使用cpp调用python函数,我已经编译了没有错误的程序,但是为什么我不能在python函数中看到print结果呢。 以下是cpp代码: #include<python2.7/Python.h> .... using namespace std; int main() { Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("import

我使用
cpp
调用
python
函数,我已经编译了没有错误的程序,但是为什么我不能在
python
函数中看到
print
结果呢。 以下是
cpp
代码:

#include<python2.7/Python.h>
....
using namespace std;
int main()
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("import os");
    PyRun_SimpleString("import string");
    PyRun_SimpleString("sys.path.append('./')"); 
    PyObject * pModule = NULL;
    PyObject * pFunc = NULL;
    PyObject * pClass = NULL;
    PyObject * pInstance = NULL;
    pModule = PyImport_ImportModule("download");
    if(!pModule)
    {
        std::cout << "there is no this file." << std::endl;
    }
    pFunc= PyObject_GetAttrString(pModule, "geturl");
    if(!pFunc)
    {
        std::cout << "there is no this func." << std::endl;
    }
    std::string url = "www";
    PyObject* args = Py_BuildValue("ss", url.c_str());
    PyEval_CallObject(pFunc, args);
    Py_DECREF(pFunc);
    Py_Finalize();
    return 0;
}
这是结果,没有错误,也没有打印错误:

root@cvm-172_16_20_84:~/klen/test/cpppython # g++ t.cpp -o printurl -lpython2.7
root@cvm-172_16_20_84:~/klen/test/cpppython # ./printurl 
root@cvm-172_16_20_84:~/klen/test/cpppython # 

如何查看
打印
,函数
geturl
是否成功运行?谢谢PyEval_CallObject函数在到达print语句之前遇到Python异常。将错误处理添加到此调用(call
PyErr\u Print
on NULL返回值)将显示引发的异常:

TypeError: geturl() takes exactly 1 argument (2 given)
根本原因是格式字符串:

Py_BuildValue("ss", url.c_str());
您正在创建一个包含两个值的元组,并将其作为参数geturl()传递。您需要传递一个只有一个值的元组。您还在这里调用未定义的行为,因为您没有提供第二个字符串指针

通过只传递一个值的元组来解决此问题:

Py_BuildValue("(s)", url.c_str());
Py_BuildValue("(s)", url.c_str());