Embedding IPython in GUI apps is trivial

by

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.

About these ads

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: