Przeglądaj źródła

Now possible to lookup python attributes in a nested module.

By default, the python attributes are looked up from __main__, note that
it's now also possible to specify a module using that form:
<ModuleName1>.<ModuleName2>
Jean-Christophe Fillion-Robin 14 lat temu
rodzic
commit
5da0576147

+ 30 - 3
Libs/Scripting/Python/Core/ctkAbstractPythonManager.cpp

@@ -173,12 +173,39 @@ void ctkAbstractPythonManager::setInitializationFunction(void (*initFunction)())
 }
 
 //----------------------------------------------------------------------------
-QStringList ctkAbstractPythonManager::pythonAttributes(const QString& pythonVariableName) const
+QStringList ctkAbstractPythonManager::pythonAttributes(const QString& pythonVariableName,
+                                                       const QString& module) const
 {
   Q_ASSERT(PyThreadState_GET()->interp);
   PyObject* dict = PyImport_GetModuleDict();
-  PyObject* object = PyDict_GetItemString(dict, "__main__");
-  Py_INCREF(object);
+
+  // Split module by '.' and retrieve the object associated if the last module
+  PyObject* object = 0;
+  PyObject* prevObject = 0;
+  QStringList moduleList = module.split(".", QString::SkipEmptyParts);
+  foreach(const QString& module, moduleList)
+    {
+    object = PyDict_GetItemString(dict, module.toAscii().data());
+    if (prevObject) { Py_DECREF(prevObject); }
+    if (!object)
+      {
+      break;
+      }
+    Py_INCREF(object);
+    dict = PyModule_GetDict(object);
+    prevObject = object;
+    }
+  if (!object)
+    {
+    return QStringList();
+    }
+
+//  PyObject* object = PyDict_GetItemString(dict, module.toAscii().data());
+//  if (!object)
+//    {
+//    return QStringList();
+//    }
+//  Py_INCREF(object);
 
   if (!pythonVariableName.isEmpty())
     {

+ 3 - 2
Libs/Scripting/Python/Core/ctkAbstractPythonManager.h

@@ -62,8 +62,9 @@ public:
   void setInitializationFunction(void (*initFunction)());
 
   /// Given a python variable name, lookup its attributes and return them in a string list.
-  /// \note The variable is looked up from __main__
-  QStringList pythonAttributes(const QString& pythonVariableName) const;
+  /// \note By default the attributes are looked up from __main__
+  QStringList pythonAttributes(const QString& pythonVariableName,
+                               const QString& module = QLatin1String("__main__")) const;
 
 signals: