如何从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异常。将错误处理添加到此调用(callPyErr\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());