我在 Python 2.7 中使用 boost::python。我想为对 boost::python::eval 的调用启用 Python 3.0 风格的除法,就像从使用
的 Python 程序中一样from __future__ import division
这看起来应该可行,尽管它会引入所有 future ,而不仅仅是除法:
boost::python::object mainModule = boost::python::import( "__main__" );
boost::python::object mainNamespace = mainModule.attr( "__dict__" );
mainNamespace[ "__future__" ] = boost::python::import( "__future__" );
return boost::python::eval(
myExpression,
mainNamespace,
mainNamespace );
不幸的是,该表达式仍然使用 Python 2.x 样式除法求值。
在 boost::Python 中启用 future 的正确方法是什么?
如何使用 boost::python 导入单个方法而不是整个库?
最佳答案
似乎最好的方法是使用脚本初始化解释器,该脚本从您想要的future 导入功能。
您可以使用 exec 和 import 语句导入模块的子集。由于 future 的工作方式,即向 exec 语句编译的代码提供指令,您不能简单地导入 exec 然后执行评估。
文档指出:
A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. If an interpreter is started with the -i option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed.
通过执行具有所需 future 导入的脚本,可以初始化 Python C API 中的解释器以使用 future 。我无法让它工作。但我可能错误地使用了 API。
另一种方法是如下所示:
boost::python::object main_module = boost::python::import("__main__");
boost::python::object main_namespace = main_module.attr("__dict__");
std::string evalString = "3/2";
std::stringstream evalStringFunction;
evalStringFunction << "from __future__ import division\n";
evalStringFunction << "def evalWithFuture(): return " << evalString;
boost::python::exec(evalStringFunction.str().c_str(), main_namespace,
main_namespace);
boost::python::object result = boost::python::eval("evalWithFuture()", main_namespace, main_namespace);
这里的想法是函数 evalWithFuture 将使用 future import 进行编译。因为它是一个表达式,所以您可以在求值调用中使用它,并且它将使用正确的 future 除法运算符。
关于python - 你如何在 boost::python 中使用 "from __future__ import division"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45045952/