2016-04-21 72 views
3

我在C++項目中運行嵌入式Python 2.7解釋器,我想盡可能地優化解釋器。我希望這樣做的一種方法是使用__debug__變量禁用我的調試語句。我還想通過運行帶有字節碼優化的Python(即-O標誌)來實現任何可能的性能提升。如何從C++初始化一個嵌入式Python解釋器並進行字節碼優化?

This Stack Overflow question解決了變量__debug__的使用,並指出可以通過運行Python -O來關閉它。但是,對於使用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(); 
} 

回答

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