【问题标题】:How can I initialize an embedded Python interpreter with bytecode optimization from C++?如何使用 C++ 的字节码优化初始化嵌入式 Python 解释器?
【发布时间】:2016-08-15 02:35:05
【问题描述】:

我在我的 C++ 项目中运行嵌入式 Python 2.7 解释器,我想尽可能优化解释器。我想这样做的一种方法是使用__debug__ 变量禁用我的调试语句。我还希望通过运行带有字节码优化的 Python(即-O 标志)来实现任何可能的性能提升。

This Stack Overflow question 解决了__debug__ 变量的使用问题,并指出可以通过使用-O 运行Python 来关闭它。但是,对于使用 C++ 钩子创建的嵌入式解释器,显然不能传递此标志。

下面是我的嵌入式解释器初始化代码。该代码并不是要单独运行,而是应该让您了解我正在使用的环境。有什么方法可以更改或添加到这些函数调用中,以指定嵌入式解释器应应用字节码优化,将__debug__ 变量设置为False,并且通常以“发布”模式而不是“调试”模式运行?

void PythonInterface::GlobalInit() {
  if(GLOBAL_INITIALIZED) return;
  PY_MUTEX.lock();
  const char *chome = getenv("NAO_HOME");
  const char *cuser = getenv("USER");
  string home = chome ? chome : "", user = cuser ? cuser : "";
  if(user == "nao") {
    std::string scriptPath = "/home/nao/python:";
    std::string swigPath = SWIG_MODULE_DIR ":";
    std::string corePath = "/usr/lib/python2.7:";
    std::string modulePath = "/lib/python2.7";
    setenv("PYTHONPATH", (scriptPath + swigPath + corePath + modulePath).c_str(), 1);
    setenv("PYTHONHOME", "/usr", 1);
  } else {
    std::string scriptPath = home + "/core/python:";
    std::string swigPath = SWIG_MODULE_DIR;
    setenv("PYTHONPATH", (scriptPath + swigPath).c_str(), 1);
  }

  printf("Starting initialization of Python version %s\n", Py_GetVersion());
  Py_InitializeEx(0); // InitializeEx(0) turns off signal hooks so ctrl c still works
  GLOBAL_INITIALIZED = true;
  PY_MUTEX.unlock();
}

void PythonInterface::Init(VisionCore* core) {
  GlobalInit();
  PY_MUTEX.lock();
  CORE_MUTEX.lock();
  CORE_INSTANCE = core;
  thread_ = Py_NewInterpreter();
  PyRun_SimpleString(
    "import pythonswig_module\n"
    "pythonC = pythonswig_module.PythonInterface().CORE_INSTANCE.interpreter_\n"
    "pythonC.is_ok_ = False\n"
    "from init import *\n"
    "init()\n"
    "pythonC.is_ok_ = True\n"
  );
  CORE_MUTEX.unlock();
  PY_MUTEX.unlock();
}

【问题讨论】:

    标签: c++ python-2.7 embed


    【解决方案1】:

    我通过在调用Py_InitializeEx(0) 之前设置PYTHONOPTIMIZE 环境变量解决了这个问题:

    /* ... snip ... */
    setenv("PYTHONOPTIMIZE", "yes", 0);
    printf("Starting initialization of Python version %s\n", Py_GetVersion());
    Py_InitializeEx(0); // InitializeEx(0) turns off signal hooks so ctrl c still works
    /* ... snip ... */
    

    【讨论】:

      猜你喜欢
      • 2011-12-06
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多