首页 > 解决方案 > 如何打印 PyRun_String 返回的对象?

问题描述

我想知道如何使用Pyrun_String.

我已经尝试过使用PyUnicode_DATAand PyObject_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);

标签: pythoncpython-c-api

解决方案


您可以使用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的,因为那是整个脚本的“返回值”。


推荐阅读