This notebook originally appeared as a post on Pythonic Perambulations by Jake Vanderplas.
Note: recent releases of IPython/Jupyter greatly streamline this kind of communication, and the approach in this post will no longer work as shown here.
I've been working with javascript and the IPython notebook recently, and found myself in need of a way to pass data back and forth between the Javascript runtime and the IPython kernel. There's a bit of information about this floating around on various mailing lists and forums, but no real organized tutorial on the subject. Partly this is because the tools are relatively specialized, and partly it's because the functionality I'll outline here is planned to be obsolete in the 2.0 release of IPython.
Nevertheless, I thought folks might be interested to hear what I've learned. What follows are a few basic examples of moving data back and forth between the IPython kernel and the browser's javascript. Note that if you're viewing this statically (i.e. on the blog or on nbviewer) then the javascript calls below will not work: to see the code in action, you'll need to download the notebook and open it in IPython.
The key functionality needed for interaction between javascript and the
IPython kernel is the kernel
object
in the IPython Javascript package.
A python statement can be executed from javascript as follows:
var kernel = IPython.notebook.kernel;
kernel.execute(command);
where command
is a string containing python code.
Here is a short example where we use HTML elements and javascript callbacks
to execute a statement in the Python kernel from Javascript, using the
kernel.execute
command:
After pressing above
with the default arguments, the value of the variable
foo
is set in the Python kernel, and can be
accessed from Python:
There was an error when executing cell [2]. Please run Voilà with --show_tracebacks=True or --debug to see the error message, or configure VoilaConfiguration.show_tracebacks.