python - 如何打印 PyRun_String 返回的对象?
问题描述
我想知道如何使用Pyrun_String
.
我已经尝试过使用PyUnicode_DATA
and 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, 2, 3)
None
$ ./x 'x = {"a": 1}; x; x["a"]'
{'a': 1}
1
None
你总是会得到一个额外 None
的,因为那是整个脚本的“返回值”。
推荐阅读
- html - 带有滚动和下拉菜单的引导 NavSide
- python - 在 S3 上为 QuickSight 创建包含嵌套 JSON 文件的数据管道
- android - Xamarin Android Manifest 生成重复行
- r - 如何从闪亮的编辑数据表中提取数据
- wordpress - 带有 wordpress api 的 Ionic v3 适用于 android 但不适用于 ios
- python - 为什么我们在调用某些函数时放置 () 而在 python 中却没有?
- r - 如何在 R 的管道中添加条件
- java - 最终用户可以使用哪些 Braintree 业务对象 ID
- couchdb - 允许非管理员读/写任何 CouchDB 数据库
- sql - 如何递归地对按另一列分组的列求和