Posts Tagged ‘gui’

Embedding IPython in GUI apps is trivial

May 15, 2008

Here is a little known secret: IPython can be trivially embedded to GUI apps with event loops. This is verified to work with Tk and Qt4, at least.

What you need to do is this:

def embed_ipython(w):
    from IPython.Shell import IPShellEmbed
    ipshell = IPShellEmbed(user_ns = dict(w = w))
    ipshell()

Here ‘w’ is a central object of some kind that you want to expose to IPython (to manipulate, test various methods, etc).

My GUI app initialization is like this:

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    embed_ipython(window)
    sys.exit(app.exec_())

What may be nonobvious here is that embed_ipython() call never returns. There is “secret sauce” in at least Qt4 and Tk that allows the GUI event loop to proceed while IPython read-eval-print loop is being handled (the same sauce that allows you to operate GUIs in standard interactive python prompt). One would intuitively guess that surely the REPL should be running in a separate thread, but this is not the case. While the UI event loop (or IPython) is doing something time-consuming, the other party will be blocked for that time – but there is the huge benefit that everything occurs in the same thread, that of the GUI event loop.