Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. void ModifierWidgetPythonScript::openScript(QString fileName)
  2. {
  3.     QFileInfo fileInfo(fileName);
  4.  
  5.     /*
  6.      * Equivalent to:
  7.      *  import sys
  8.      *  del sys.modules['module']
  9.      */
  10.     if(py_->module)
  11.     {
  12.         PyObject* modules = PyImport_GetModuleDict();
  13.         PyDict_DelItem(modules, PyUnicode_FromString(PyModule_GetName(py_->module)));
  14.     }
  15.  
  16.     // Release references to previous module + callback functions
  17.     py_->flushFunction.reset();
  18.     py_->applyFunction.reset();
  19.     py_->module.reset();
  20.  
  21.     /*
  22.      * Need to first change the path to the directory where the script lies, by
  23.      * adding the path to the script to sys.path. The following checks if the
  24.      * path already exists in sys.path, and adds it if it doesnt.
  25.      */
  26.     std::wstring pathToAdd = fileInfo.absolutePath().toStdWString();
  27.     PyObject* pySysPath = PySys_GetObject("path");
  28.     PythonObject<> pyPathToAdd = PyUnicode_FromWideChar(pathToAdd.c_str(), wcslen(pathToAdd.c_str()));
  29.     int pyLen = PyList_Size(pySysPath);
  30.     for(int i = 0; i != pyLen; ++i)
  31.     {
  32.         PyObject* item = PyList_GET_ITEM(pySysPath, i);
  33.         if(PyUnicode_Compare(item, pyPathToAdd) == 0)
  34.             goto path_already_added;
  35.     }
  36.     PyList_Append(pySysPath, pyPathToAdd.steal());
  37.     path_already_added:
  38.  
  39.     PythonObject<> scriptFile = PyUnicode_DecodeFSDefault(fileInfo.fileName().replace(".py", "").toUtf8().data());
  40.     if(scriptFile == NULL)
  41.     {
  42.         defaultLogger.logError("Failed to load python script %s, file name to unicode conversion failed.", fileName.toLatin1().data());
  43.         return;
  44.     }
  45.     py_->module = PyImport_Import(scriptFile);
  46.     if(py_->module == NULL)
  47.     {
  48.         PythonInterpreter_logError(QString("Failed to import script " + fileName).toLatin1().data());
  49.         return;
  50.     }
  51.  
  52.     // other stuff
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement