Advertisement
r-englund

Python Initialization

Jan 8th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. void importModule(const std::string& moduleName) {
  2.     const static std::string __key__ = "__";
  3.     char* key = new char[moduleName.size() + 5];
  4.     sprintf(key, "__%s__", moduleName.c_str());
  5.     if (PyDict_GetItemString(mainDict_, key) == nullptr) {
  6.         PyObject* pMod = PyImport_ImportModule(moduleName.c_str());
  7.         if (nullptr != pMod) {
  8.             PyDict_SetItemString(mainDict_, key, pMod);
  9.         } else {
  10.             LogWarn("Failed to import python module: " << moduleName);
  11.         }
  12.     }
  13.     delete[] key;
  14. }
  15.  
  16.  
  17. void initPython(){
  18.  
  19.     wchar_t programName[] = L"PyInviwo";
  20.     Py_SetProgramName(programName);
  21. #ifdef WIN32
  22.     Py_NoSiteFlag = 1;
  23. #endif
  24.     Py_InitializeEx(false);
  25.  
  26.     if (!Py_IsInitialized()) {
  27.         LogError("Python is not Initialized");
  28.         return;
  29.     }
  30.  
  31.     PyEval_InitThreads();
  32.     mainDict_ = PyDict_New();
  33.     modulesDict_ = PyImport_GetModuleDict();
  34.     importModule("builtins");
  35.     importModule("sys");
  36.     //importModule("os");
  37.     //importModule("glob");
  38.     //importModule("random");
  39.  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement