【问题标题】:PyRun_String returns a NoneType objectPyRun_String 返回一个 NoneType 对象
【发布时间】:2020-06-04 10:07:37
【问题描述】:

我正在用 c++ 编写一个 base64 函数。我想使用 python 进行编码并将结果返回给我的 c++ 程序。这是我的代码:

string EncodeBase64(string str)
{
    Py_Initialize();
    PyObject* ret1 = NULL;
    PyObject* ret2 = NULL;
    PyObject* main = PyImport_AddModule("__main__");
    PyObject* _g = PyModule_GetDict(main);
    PyObject* _l = PyDict_New();
    string py = "str(base64.b64encode('" + str + "'.encode('utf-8')), 'utf-8')";
    string pyb = "base64.b64encode('" + str + "'.encode('utf-8'))";
    char* rec = new char[8192];
    cout << "Request 1: " << py << endl;
    cout << "Request 2: " << pyb << endl;
    PyRun_SimpleString("import base64");
    ret1 = PyRun_String(py.c_str(), Py_file_input, _g, _l);
    main = PyImport_AddModule("__main__");
    _g = PyModule_GetDict(main);
    _l = PyDict_New();
    ret2 = PyRun_String(pyb.c_str(), Py_file_input, _g, _l);
    if (!ret1)
    {
        cout << "Can not get return value 1." << endl;
    }
    else
    {
        cout << "Type of Return Value 1: " << ret1->ob_type->tp_name << endl;
    }
    if (!ret2)
    {
        cout << "Can not get return value 1." << endl;
    }
    else
    {
        cout << "Type of Return Value 2: " << ret1->ob_type->tp_name << endl;
    }
    Py_Finalize();
    return "";
}

我输入一个字符串“123456”,程序输出如下:

Request 1: str(base64.b64encode('123456'.encode('utf-8')), 'utf-8')
Request 2: base64.b64encode('123456'.encode('utf-8'))
Type of Return Value 1: NoneType
Type of Return Value 2: NoneType

我尝试将请求字符串输入python,运行正常。结果如下:

C:\Users\15819>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import base64
>>> str(base64.b64encode('123456'.encode('utf-8')), 'utf-8')
'MTIzNDU2'
>>> base64.b64encode('123456'.encode('utf-8'))
b'MTIzNDU2'

我想知道为什么PyRun_String 的返回值是NoneType 以及如何让它返回正确的值。 我的环境信息:

System: Windows 10 1909 x64
C++IDE: Visual Studio 2019 Professional
Python version: 3.7.4
Project Config: Release X64

【问题讨论】:

    标签: python c++ python-3.x visual-studio-2019 python-c-api


    【解决方案1】:

    传递Py_file_inputstart 参数在效果上类似于将'exec' 传递给the compile built-in;这意味着像运行一个完整的模块一样运行它(把它想象成询问import modulename 的“结果”;没有“结果”)。

    只有表达式计算为非平凡/非None 结果,而不是模块或语句,因此对于任何start 参数,但Py_eval_input(等效于'eval' 模式compile),结果将永远是None(它只是None,因为他们需要返回一些东西来区分NULL失败和其他东西成功,eval模式需要PyObject*返回而不是布尔值)。如果要计算表达式并获得结果,则必须将 Py_eval_input 用作 start 参数。

    【讨论】:

      猜你喜欢
      • 2021-02-06
      • 2021-06-24
      • 2021-03-12
      • 2019-01-12
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 2018-11-29
      相关资源
      最近更新 更多