【发布时间】:2018-11-02 09:07:14
【问题描述】:
我想使用 Pybind11 或直接使用 Python C API 将此 Python 代码转换为 C++ 代码:
import ast
code = "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
知道如何正确实现这一点吗?
【问题讨论】:
-
您应该发布minimal reproducible example,由于某种原因缺少框架对象,这与您发布的代码无关。您发布的代码很好。
-
我的代码中没有框架对象,它是 Python 解释器的内部对象。发布的代码不好,解释器抱怨,因为我没有将全局命名空间传递给
exec函数。 -
唯一缺少的是所需头文件的
include,我将编辑问题。
标签: python c++ abstract-syntax-tree python-c-api pybind11