Browse Source

Add python3 support

Ifdef where necessary, use statements valid for python 3 and 2.6+ where
possible.
Caspar Goch 7 years ago
parent
commit
7d209d99ff

+ 1 - 1
Applications/ctkSimplePythonShell/Testing/Python/ctkWidgetsTest.py

@@ -12,7 +12,7 @@ pythonManager.executeString("variableInPythonConsole=523")
 try:
   print("variableInPythonConsole was successfully set to {0}".format(variableInPythonConsole))
 except:
-  print "PythonManager.executeString failed"
+  print("PythonManager.executeString failed")
   qt.QApplication.exit(1)
 
 if not _ctkPythonConsoleInstance.isInteractive:

+ 13 - 13
Applications/ctkSimplePythonShell/Testing/Python/vtkPythonSmoke.py

@@ -9,43 +9,43 @@ try:
   import vtk
 
 except:
-  print "Cannot import vtk"
+  print("Cannot import vtk")
   qt.QApplication.exit(1)
 try:
-  print dir(vtk)
+  print(dir(vtk))
 except:
-  print "Cannot print dir(vtk)"
+  print("Cannot print dir(vtk)")
   qt.QApplication.exit(1)
 
 try:
   try:
     try:
       o = vtk.vtkLineWidget()
-      print "Using Hybrid"
+      print("Using Hybrid")
     except:
       o = vtk.vtkActor()
-      print "Using Rendering"
+      print("Using Rendering")
   except:
     o = vtk.vtkObject()
-    print "Using Common"
+    print("Using Common")
 except:
-  print "Cannot create vtkObject"
+  print("Cannot create vtkObject")
   qt.QApplication.exit(1)
 
 try:
-  print o
-  print "Reference count: %d" % o.GetReferenceCount()
-  print "Class name: %s" % o.GetClassName()
+  print(o)
+  print("Reference count: %d" % o.GetReferenceCount())
+  print("Class name: %s" % o.GetClassName())
 except:
-  print "Cannot print object"
+  print("Cannot print object")
   qt.QApplication.exit(1)
 
 try:
   b = vtk.vtkObject()
   d = b.SafeDownCast(o)
-  print b, d
+  print(b, d)
 except:
-  print "Cannot downcast"
+  print("Cannot downcast")
   qt.QApplication.exit(1)
 
 qt.QApplication.exit(0)

+ 1 - 1
Applications/ctkSimplePythonShell/Testing/Python/wrappedVTKQInvokableTest.py

@@ -7,7 +7,7 @@ import qt
 from vtk import *
 
 t = _testWrappedVTKQInvokableInstance.getTable()
-print t.GetClassName()
+print(t.GetClassName())
 
 t2 = vtkTable()
 _testWrappedVTKQInvokableInstance.setTable(t2)

+ 1 - 1
Applications/ctkSimplePythonShell/Testing/Python/wrappedVTKSlotTest.py

@@ -7,7 +7,7 @@ import qt
 from vtk import *
 
 t = _testWrappedVTKSlotInstance.getTable()
-print t.GetClassName()
+print(t.GetClassName())
 
 t2 = vtkTable()
 _testWrappedVTKSlotInstance.setTable(t2)

+ 20 - 2
CMake/ctkMacroWrapPythonQtModuleInit.cpp.in

@@ -48,14 +48,32 @@ void copyAttributes(PyObject* orig_module, PyObject* dest_module)
     }
 }
 } // end of anonymous namespace
+//-----------------------------------------------------------------------------
+#if PY_MAJOR_VERSION >= 3
+
+static struct PyModuleDef moduledef = {
+    PyModuleDef_HEAD_INIT,
+    "@TARGET_CONFIG@PythonQt",                 /* m_name */
+    "The @TARGET_CONFIG@PythonQt module",      /* m_doc */
+    -1,                                        /* m_size */
+    Py@TARGET_CONFIG@PythonQt_ClassMethods,    /* m_methods */
+    NULL,                                      /* m_reload */
+    NULL,                                      /* m_traverse */
+    NULL,                                      /* m_clear */
+    NULL,                                      /* m_free */
+  };
 
+#endif
 //-----------------------------------------------------------------------------
 void init@TARGET_CONFIG@PythonQt()
 {
   static const char modulename[] = "@TARGET_CONFIG@PythonQt";
   PyObject *m;
-
-  m = Py_InitModule((char*)modulename, Py@TARGET_CONFIG@PythonQt_ClassMethods);
+  #if PY_MAJOR_VERSION >= 3
+    m = PyModule_Create(&moduledef);
+  #else
+    m = Py_InitModule((char*)modulename, Py@TARGET_CONFIG@PythonQt_ClassMethods);
+  #endif
   extern void PythonQt_init_@WRAPPING_NAMESPACE_UNDERSCORE@_@TARGET_CONFIG@(PyObject*);
   PythonQt_init_@WRAPPING_NAMESPACE_UNDERSCORE@_@TARGET_CONFIG@(m);
 

+ 6 - 6
CMake/ctk_compile_python_scripts.cmake.in

@@ -55,16 +55,16 @@ def ctk_compile_file(fullname, ddir=None, force=0, rx=None, quiet=0):
                 except IOError:
                     pass
             if not quiet:
-                print 'Compiling', fullname, '...'
+                print('Compiling', fullname, '...')
             try:
                 ok = py_compile.compile(fullname, None, dfile, True)
-            except py_compile.PyCompileError,err:
+            except py_compile.PyCompileError as err:
                 if quiet:
-                    print 'Compiling', fullname, '...'
-                print err.msg
+                    print('Compiling', fullname, '...')
+                print(err.msg)
                 success = 0
-            except IOError, e:
-                print 'Sorry', e
+            except IOError as e:
+                print('Sorry', e)
                 success = 0
             else:
                 if ok == 0:

+ 1 - 1
Libs/Scripting/Python/Core/Python/ctk/__init__.py.in

@@ -13,7 +13,7 @@ for kit in __kits_to_load:
     kits.append(kit)
   except ImportError as detail:
     if _CTK_VERBOSE_IMPORT:
-      print detail
+      print(detail)
 
 def add_methodclass_to_ctkWorkflowStep_or_ctkWorkflowWidgetStep(workflowstep_class):
 

+ 1 - 1
Libs/Scripting/Python/Core/Python/qt/__init__.py.in

@@ -11,7 +11,7 @@ for kit in __kits_to_load:
      exec "from PythonQt.Qt%s import *" % (kit)
    except ImportError as detail:
      if _CTK_VERBOSE_IMPORT:
-       print detail
+       print(detail)
 
 # Removing things the user shouldn't have to see.
 del __kits_to_load, _CTK_VERBOSE_IMPORT

+ 7 - 2
Libs/Scripting/Python/Core/ctkAbstractPythonManager.cpp

@@ -306,6 +306,11 @@ void ctkAbstractPythonManager::executeFile(const QString& filename)
   if (main)
     {
     QString path = QFileInfo(filename).absolutePath();
+    #if PY_MAJOR_VERSION >= 3
+      QString raiseWithTraceback("      raise(_ctk_executeFile_exc_info[1](None)).with_traceback()");
+    #else
+      QString raiseWithTraceback("      raise _ctk_executeFile_exc_info[1], None, _ctk_executeFile_exc_info[2]");
+    #endif
     // See http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html
     QStringList code = QStringList()
         << "import sys"
@@ -315,13 +320,13 @@ void ctkAbstractPythonManager::executeFile(const QString& filename)
         << "_ctk_executeFile_exc_info = None"
         << "try:"
         << QString("    execfile('%1', _updated_globals)").arg(filename)
-        << "except Exception, e:"
+        << "except Exception as e:"
         << "    _ctk_executeFile_exc_info = sys.exc_info()"
         << "finally:"
         << "    del _updated_globals"
         << QString("    if sys.path[0] == '%1': sys.path.pop(0)").arg(path)
         << "    if _ctk_executeFile_exc_info:"
-        << "        raise _ctk_executeFile_exc_info[1], None, _ctk_executeFile_exc_info[2]";
+        << raiseWithTraceback;
     this->executeString(code.join("\n"));
     //PythonQt::self()->handleError(); // Clear errorOccured flag
     }