IPython Notebook: programmatically launch a cell from JavaScript

So, I play a couple of times with an IPython laptop, and I like it! But now I need to do something a little weird:

I have a markdown cell; it has an HTML input and a button, and some JavaScript is attached to the button, which will take the contents of the input and enter it into the python core. Here is the cell:

<h3>Use JS to pass DOM info to Python kernel: </h3> <input id='testinput' value='FragmentId'></input> <button id='testComms' onclick='JS2PY()'>:D</button> <script type="text/javascript"> function JS2PY(){ var input = document.getElementById('testinput').value, kernel = IPython.notebook.kernel; kernel.execute('testVar = "' + input + '"'); } </script> 

It works like a charm! Then I have a python code cell; it does some ROOT stuff and makes the plot based on any value that was entered into the python core from the specified cell. Here's the python cell:

 def testfunc(): from ROOT import TH1, TFile, TTree import rootnotes, numpy c2 = rootnotes.canvas("treeData", (600,400)) testfile = TFile("fragment27422_000.root") testtree = testfile.Get("FragmentTree") buff = numpy.zeros(1, dtype=float) testtree.Branch(testVar, buff) testtree.Draw(testVar) return c2 testfunc() 

Also the problem does not work, if I manually go over and run the cell - fine! But I really want this python cell to start automatically when I click this button in the markdown cell above, after moving the testVar variable. Apologies and thanks in advance are just two days for python for me, so maybe something is really simple.

+7
ipython-notebook
source share
1 answer

Solution / workaround: instead of directly launching other cells, we can call the python functions defined in other cells and get feedback between JavaScript and the python core followed by a callback, all through IPython.notebook.kernel.execute ; something like this code cell:

 %%HTML <div id='testwrap'> <input id='varname'></input> <img id='imgtarget'></img> <button id='fetchplot' onclick='exec_code()'>Plot</button> </div> <script type="text/Javascript"> function handle_output(out_type, out){ document.getElementById('imgtarget').src = 'data:image/png;base64,' + out.data['image/png']; } function exec_code(){ var kernel = IPython.notebook.kernel; var callbacks = {'output' : handle_output}; kernel.execute('testVar = "' + document.getElementById('varname').value + '"'); kernel.execute('testfunc(testVar)', callbacks, {silent:false}); } </script> 

The first kernel.execute discards some data to the kernel from the DOM, and the second uses a callback to work in JS so that the python testfunc function (defined in some other cell) returns.

Big increases to http://jakevdp.imtqy.com/blog/2013/06/01/ipython-notebook-javascript-python-communication/ for the bones of this solution!

+9
source share

All Articles