我想使用 Pybind11 或直接使用 Python C API 将此 Python 代码转换为 C++ 代码:import astcode = "print('Hello World!')"code_ast = ast.parse(code, mode="exec") # "code" being a string containing code# ... perform some modifications on "code_ast"exec(compile(code_ast, filename="<ast>", mode="exec"))这是我目前使用 Pybind11 的内容:#include <iostream>#include "pybind11/embed.h"namespace py = pybind11;std::string code = "print('Hello World!')";py::module ast = py::module::import("ast");py::module builtins = py::module::import("builtins");py::object code_ast = ast.attr("parse")(code, "<unknown>", "exec");// ... perform some modifications on "code_ast"py::object compiled_code = builtins.attr("compile")(code_ast, "<ast>", "exec");builtins.attr("exec")(compiled_code);不幸的是,最后一行 C++ 代码引发了一个运行时错误:SystemError: frame does not exist.我不确定我是否理解此错误,我尝试将globals和传递locals给exec,但没有解决问题。编辑:通过时globals,它说:SystemError: <built-in function globals> returned NULL without setting an error关于如何正确实现这一目标的任何想法?
1 回答
噜噜哒
TA贡献1784条经验 获得超7个赞
我找到了答案,我没有使用globalsPybind11的函数,而是使用 Python ( builtins.attr("globals")())的内置函数。
这是工作版本:
py::module ast = py::module::import("ast");
py::module builtins = py::module::import("builtins");
py::object code_ast = ast.attr("parse")(code, "<unknown>", "exec");
// ... perform some modifications on "code_ast"
py::object compiled_code = builtins.attr("compile")(code_ast, "<ast>", "exec");
builtins.attr("exec")(compiled_code, py::globals());
添加回答
举报
0/150
提交
取消