Python: get string representation of PyObject?

前端 未结 5 1288
予麋鹿
予麋鹿 2020-12-23 19:41

I\'ve got a C python extension, and I would like to print out some diagnostics.

I\'m receiving a string as a PyObject*.

What\'s the canonical way to obtain a

相关标签:
5条回答
  • 2020-12-23 20:11

    PyObject *module_name; PyUnicode_AsUTF8(module_name)

    0 讨论(0)
  • 2020-12-23 20:12

    Here is the correct answer if you are using Python 3:

    static void reprint(PyObject *obj) {
        PyObject* repr = PyObject_Repr(obj);
        PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "~E~");
        const char *bytes = PyBytes_AS_STRING(str);
    
        printf("REPR: %s\n", bytes);
    
        Py_XDECREF(repr);
        Py_XDECREF(str);
    }
    
    0 讨论(0)
  • 2020-12-23 20:17

    If you need just print the object in Python 3 you can use one of these functions:

    static void print_str(PyObject *o)
    {
        PyObject_Print(o, stdout, Py_PRINT_RAW);
    }
    
    static void print_repr(PyObject *o)
    {
        PyObject_Print(o, stdout, 0);
    }
    
    0 讨论(0)
  • 2020-12-23 20:18

    Try PyObject_Repr (to mimic Python's repr) or PyObject_Str (to mimic Python's str).

    Docs:

    Compute a string representation of object o. Returns the string representation on success, NULL on failure. This is the equivalent of the Python expression repr(o). Called by the repr() built-in function.

    0 讨论(0)
  • 2020-12-23 20:36

    Use PyObject_Repr (to mimic Python's repr function) or PyObject_Str (to mimic str), and then call PyString_AsString to get char * (you can, and usually should, use it as const char*, for example:

    PyObject* objectsRepresentation = PyObject_Repr(yourObject);
    const char* s = PyString_AsString(objectsRepresentation);
    

    This method is OK for any PyObject. If you are absolutely sure yourObject is a Python string and not something else, like for instance a number, you can skip the first line and just do:

    const char* s = PyString_AsString(yourObject);
    
    0 讨论(0)
提交回复
热议问题