【问题标题】:How to print the object returned by PyRun_String?如何打印 PyRun_String 返回的对象?
【发布时间】:2021-02-06 16:58:07
【问题描述】:

我想知道Pyrun_String的返回怎么用。

我已经尝试过使用PyUnicode_DATAPyObject_Str

if (!(pstr = PyRun_String("a = 1", Py_single_input, pGlobal, pdict)))
    exit(printf("Error while running string\n"));


// I tried this

PyObject *pstr = PyObject_Str(pstr);

void* test = PyUnicode_DATA(pstr);
printf("%s\n", (char*)test);


// or this

if (!PyArg_Parse(pstr, "s", &cstr))
    exit(printf("Bad result type\n"));
printf("%s\n", cstr);

【问题讨论】:

    标签: python c python-c-api


    【解决方案1】:

    您可以使用PyObject_Repr() 获取对象的字符串表示形式(如Python 的repr()),然后将其传递给PyUnicode_AsUTF8() 以获取UTF-8 编码的C 字符串。不要忘记先与PyUnicode_Check() 联系。

    工作示例:

    #include <stdio.h>
    #include <Python.h>
    
    int main(int argc, char **argv) {
            if (argc != 2) {
                    fprintf(stderr, "Usage: %s PYTHON_CODE\n", argv[0]);
                    return 1;
            }
    
            Py_Initialize();
            PyObject *dict = PyDict_New();
            PyObject *pstr;
    
            if (!(pstr = PyRun_String(argv[1], Py_single_input, dict, dict))) {
                    fputs("PyRun_String failed\n", stderr);
                    return 1;
            }
    
            PyObject *rep = PyObject_Repr(pstr);
    
            if (!PyUnicode_Check(rep)) {
                    fputs("repr is not unicode (this should not happen!)\n", stderr);
                    return 1;
            }
    
            const char *str_rep = PyUnicode_AsUTF8(rep);
            puts(str_rep);
    }
    

    示例输出:

    $ ./x 'a = 1'
    None
    $ ./x '(1,2,3)'
    (1, 2, 3)
    None
    $ ./x 'x = {"a": 1}; x; x["a"]'
    {'a': 1}
    1
    None
    

    你总是会得到一个额外的None,因为那是整个脚本的“返回值”。

    【讨论】:

    • 我正在使用 python3.9 并且 PyString_AsString 不可用:/
    • 我尝试使用 void* test = PyUnicode_DATA(rep); printf("%s\n", (char*)test).但它没有工作。
    • @auguyon 我的错,复制粘贴了错误的代码。立即检查。
    猜你喜欢
    • 2020-06-04
    • 1970-01-01
    • 2022-01-06
    • 2022-08-16
    • 2020-11-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多