2014-01-31 75 views
7

因此,我一直在玩IPython筆記本幾天,我喜歡它!但是,現在我需要做一些小小的事情:IPython Notebook:以編程方式觸發JavaScript中的單元格

我有一個降價單元;其中包含一個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> 

工程就像一個魅力!接下來,我有一個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() 

如果我手動去運行單元格,也可以工作 - 很棒!但是我真正想要的是,在推廣testVar變量之後,當單擊上面降價單元中的該按鈕時,此python單元格會自動運行。道歉和感謝提前 - 這只是我的第二天的python,所以它可能是一個非常簡單的東西。

回答

8

解決方法/解決方法:不是直接觸發其他單元格,我們可以調用其他單元格中定義的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> 

第一kernel.execute踢一些數據,將其從DOM內核,而第二個使用回調做的東西在JS與任何Python函數testfunc(在其他一些定義細胞)返回。

這個解決方案的骨頭大到http://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/

相關問題