Closing napari viewer from within python script

What is the appropriate way to close the viewer and return control to the calling program? I naively guessed using the viewer’s close() method, but this doesn’t work, as the following code never reaches the print statement (although it does close the window). What method should be called to end the with block?

import napari

with napari.gui_qt():
    viewer = napari.Viewer()
    viewer.close()
print("end")

In case it matters, I’m running this script directly from the command line, not an ipython session or jupyter notebook.

Thanks!

Hi @naten7k.

What needs to happen for the context to exit is not the viewer closing, rather the Qt event loop that has been started by the context manager needs to quit. The gui_qt() context manager actually returns the app instance, but you will need to add a brief timeout before immediately calling it’s quit method…

import napari
from qtpy.QtCore import QTimer

with napari.gui_qt() as app:
    viewer = napari.Viewer()
    time_in_msec = 1000
    QTimer().singleShot(time_in_msec, app.quit)
viewer.close()
print("end")

Works perfectly, thank you!

1 Like