1

I use cpp to call python function, I have compiled the program without errors, but why can not I see the print result in python function. here is the cpp codes:

#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;
}

here is the download.py file in the same dir

def geturl(url):
    print(url)
    print("hello")

here is result, without errors nor print:

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 # 

How can I see the print, has the function geturl run successfully? Thanks

1 Answer 1

1

The PyEval_CallObject function is encountering a Python exception before it reaches your print statements. Adding error handling to this call (call PyErr_Print on NULL return value) will show the exception being raised:

TypeError: geturl() takes exactly 1 argument (2 given)

The root cause is the format string:

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

You are creating a tuple of two values and passing that as the arguments geturl(). You need to pass a tuple with only one value. You are also invoking undefined behavior here because you haven't provided a second string pointer.

Resolve the issue by passing a tuple with only one value:

Py_BuildValue("(s)", url.c_str());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.