[vtkusers] patch for turning (almost) all VTK errors into Python exceptions

Charl P. Botha cpbotha at cpbotha.net
Wed Aug 2 12:09:25 EDT 2006


Hi there (Python)-gang,

I've made a patch for VTK 5.0 which will turn almost all VTK errors
into Python exceptions.  It works around the exception non-safety of
VTK.  Have a look here:

http://visualisation.tudelft.nl/~cpbotha/thingies/python_exceptions_vtk5.0.diff

In short, ALL instances of vtkObject descendants are instrumented with
a C++ ErrorEvent handler by the wrapping code in vtkPythonUtil.c.  The
event handler sets up a Python exception by calling PyErr_SetString or
PyErr_None, whichever is relevant.  vtkWrapPython.c generates
wrappings which check PyErr_Occurred() _after_ every VTK method call,
and return NULL if it's true, thus completing the Python exception
protocol.

For example:

>>> import vtk
>>> a = vtk.vtkXMLImageDataReader()
>>> a.SetFileName('bad filename')
>>> b = vtk.vtkMarchingCubes()
>>> b.SetInput(a.GetOutput())
>>> b.Update()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
RuntimeError: ERROR: In \build\Vtk\Io\vtkXMLReader.cxx, line 173
vtkXMLImageDataReader (013D19C0): Error opening file bad filename

Instead of stdout output or an OutputWindow, we get a neat Python
exception that we can actually do things with.  On Windows, you will
unfortunately see another error message (that of the vtkExecutive) in
an OutputWindow.  This is because the Executive is implicitly created
by pure C++ code.

Fortunately there's a way around this: a vtkOutputWindow child
(globally configured, as is usual) that invokes an ErrorEvent with the
error message instead of outputting anything, thus making use of the
ErrorEvent handler we've added in the wrapping code, and forcing
Executive (and ALL other implicitly created VTK objects) errors to be
transformed into Python exceptions as well.  I have an implementation
of this if anyone is interested.

What do VTK/Python people think?  This definitely fills a niche, and
it could be conditionally included in VTK.  The only drawback is the
extra PyErr_Occurred() call after every VTK method call, and of course
the extra line or two of Python code to set up the new
vtkEventOutputWindow).

Thanks,
Charl



More information about the vtkusers mailing list