python - 你如何在 boost::python 中使用 "from __future__ import division"?

标签 python c++ boost boost-python

我在 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 样式除法求值。

  1. 在 boost::Python 中启用 future 的正确方法是什么?

  2. 如何使用 boost::python 导入单个方法而不是整个库?

最佳答案

  1. 似乎最好的方法是使用脚本初始化解释器,该脚本从您想要的future 导入功能。

  2. 您可以使用 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/

相关文章:

c++ - 开罗翻转绘图

c++ - 递归 Boost.Spirit 解析的问题

c++ - 在 OpenCL 1.2 中的内核之间传递变量/内核之间的通信

c++ - 错误 C2666 类似重载

c++ - 使用 Boost 的 bool 表达式

c++ - 包括 Boost 网络库使 Windows.h 函数未定义

python - [在Python中实现图表] : are lists of connected nodes preferable over dictionaries?

python - 如何在python中有条件地选择上一行的值?

python - OSError - Errno 13 权限被拒绝

c++ - 不同语言的 OpenCV 性能