问题描述
我想知道如何使用Pyrun_String
的返回值。
我已经尝试使用PyUnicode_DATA
和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);
解决方法
您可以使用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,3)
None
$ ./x 'x = {"a": 1}; x; x["a"]'
{'a': 1}
1
None
您总是以另外的None
结尾,因为那是整个脚本的“返回值”。