作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以,这几天我一直在玩 IPython notebook,我喜欢它!但是,现在我需要做一些有点花哨的事情:
我有一个 Markdown 单元格;在其中,有一个 HTML 输入和按钮,以及一些附加到按钮的 JavaScript,它将获取输入的内容,并将其注入(inject) 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>
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 函数,然后通过回调在 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
执行操作(在其他单元格中定义)返回。
关于ipython-notebook - IPython 笔记本 : programmatically trigger a cell from JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21470546/
我是一名优秀的程序员,十分优秀!