pythonmatplotlibmayavi

Python script doesn't continue until mayavi scene window closed


The following code (except the import) is executed in a loop, where there are 4 figures opened and simple graphs plotted. However, when the mayavi scene is created, the program stops and only continues, once !all! figures are closed! It stops between the print commands before/after:

from mayavi import mlab as mayavi_mlab


plot_extent = (-20, 20, 0, 30, 0, 1)
s= mayavi_mlab.surf(x, y, z, colormap='PuBu',extent=plot_extent, vmin=-0.5, vmax=0.5)

mayavi_mlab.axes(s, color=(.7, .7, .7), extent=plot_extent,ranges=(-120, 120, 0, 10J,0,1), xlabel='site i', ylabel='energy E',x_axis_visibility=True, y_axis_visibility=True, z_axis_visibility=False)
mayavi_mlab.view(azimuth=-90, elevation=35, distance=70, focalpoint=None)

print('before')        
mayavi_mlab.show()
print('after')

What am I doing wrong? platform:os x 10.9.5

Python 2.7.9 |Anaconda 2.1.0 (x86_64)| (default, Dec 15 2014, 10:37:34) [GCC 4.2.1 (Apple Inc. build 5577)] on darwin


Solution

  • The docs for mayavi.mlab.show state:

    By default, this function simply creates a GUI and starts its event loop if needed.

    Therefore mayavi_mlab.show() will start the main event loop and not return until this loop has finished. But that's just the case, when all figures have been closed and no UI is left to be shown.

    If you don't want this part of the code to be blocking, you should use the threading, multiprocessing or any other concurrent library or method. If you want to achieve this fastly, os.fork() might suffice:

    print('before')
    if os.fork() == 0:
        try:
            mayavi_mlab.show()
        finally:
            os._exit(os.EX_OK)
    print('after')
    

    But keep in mind, that this will leave you with a Zombie processes.