gpt4 book ai didi

ipython-notebook - IPython 笔记本 : programmatically trigger a cell from JavaScript

转载 作者:行者123 更新时间:2023-12-04 07:02:20 25 4
gpt4 key购买 nike

所以,这几天我一直在玩 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>

奇迹般有效!接下来我有一个 python 代码单元;它做了一些 ROOT 的东西,并根据从上述单元注入(inject)到 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()

如果我手动运行单元格也可以正常工作 - 太棒了!但我真正想要的是,当我点击上面markdown单元格中的那个按钮时,这个python单元格会自动运行,在提升 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 执行操作(在其他单元格中定义)返回。

大涨到 http://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/对于这个解决方案的骨头!

关于ipython-notebook - IPython 笔记本 : programmatically trigger a cell from JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21470546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com