我正在C++项目中运行嵌入式Python 2.7解释器,并且我想尽可能地优化解释器。我要执行此操作的一种方法是使用__debug__变量禁用调试语句。我还想认识到由于使用字节码优化(即-O标志)运行Python而导致的任何性能提升。

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();
}

最佳答案

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

/* ... 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 ... */

关于c++ - 如何使用C++中的字节码优化来初始化嵌入式Python解释器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36777274/

10-12 23:52