IPython Notebook:以编程方式从JavaScript触发单元格

Bil*_*lls 8 ipython-notebook

所以,我一直在玩IPython笔记本几天,我喜欢它!但是,现在我需要做一些有点花哨的事情:

我有一个降价单元; 在其中,有一个HTML输入和按钮,以及一些附加到按钮的JavaScript,它将获取输入的内容,并将其注入到python内核中.这是细胞:

<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>
Run Code Online (Sandbox Code Playgroud)

奇迹般有效!接下来我有一个python代码单元; 它做了一些ROOT的东西,并根据从上面的单元格注入到python内核中的任何值来创建一个图.这是python单元格:

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()
Run Code Online (Sandbox Code Playgroud)

如果我手动去运行单元格也没问题 - 太棒了!但是我真正想要的是,在推广testVar变量后,当我点击上面的降价单元格中的那个按钮时,这个python单元会自动运行.抱歉并提前感谢 - 这对我来说只是python的第二天,所以它可能非常简单.

Bil*_*lls 10

解决方案/解决方法:我们不是直接触发其他单元格,而是调用其他单元格中定义的python函数,然后在JavaScript和python内核之间进行往返,之后回调,全部通过IPython.notebook.kernel.execute; 像这个代码单元格:

%%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>
Run Code Online (Sandbox Code Playgroud)

第一个kernel.execute从DOM中将一些数据提取到内核,第二个使用回调在JS中执行任何内容,无论python函数testfunc(在某些其他单元格中定义)返回.

对于此解决方案的骨骼,请大家到http://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/!