我正在尝试通过javascript直接执行python代码:
在javascript控制台中,我输入:IPython.notebook.kernel.execute("2+2")
但是我得到了一个奇怪的输出:"6CEA73CC644648DDA978FDD6A913E519"
有没有办法利用所有可用的IPython javascript函数,从javascript控制台运行python代码,如图所示?我确信有一种方法,但我已经努力了太久,我想我应该在这里发帖。
(我需要这个来在IPython上构建一个应用程序)
提前感谢!
发布于 2018-09-16 01:10:48
您可以使用Jupyter.notebook.kernel.execute()
函数从JavaScript调用Python代码执行。
依靠Craig Dennis提供的这个gist,您可以将此代码插入到Jupyter cell中并运行它
%%javascript
window.executePython = function(python) {
return new Promise((resolve, reject) => {
var callbacks = {
iopub: {
output: (data) => resolve(data.content.text.trim())
}
};
Jupyter.notebook.kernel.execute(`${python}`, callbacks);
});
}
function Log_out(r)
{ console.log(r); };
var code =
'for i in range(1,6):'+
' print( "#" + str(i))';
window.executePython( code )
.then(result => Log_out(result)); // Log out
结果将被输出到浏览器javascript控制台。
发布于 2015-10-09 22:00:37
你知道这篇博文吗?http://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/
我认为他使用的方法不再有效,但也许它可以让你进步一步
发布于 2021-10-15 01:10:57
在花了两天的时间之后,我找到了一个对我有效的解决方案。
为了运行Python代码,我简单地使用了“Jupyter.notebook.kernel.execute”。为了得到答案,我在这个链接上找到了有用的信息:https://jupyter-notebook.readthedocs.io/en/stable/comms.html
from ipykernel.comm import Comm
js_input = [] #case willing to track
def func_edit(cobj,text):
my_comm = Comm(target_name=cobj) #this is the callback
my_comm.send('' if text == '' else 'Return: ' + text)
global js_input
js_input.append(f'origin={cobj} text={text}')
from IPython.display import display, HTML
html = """
<script>
var comm_name = "this_control";
function fcalc(x)
{
// here I am passing to the Python function the value to edit and the address for getting the return value
IPython.notebook.kernel.execute("func_edit('" + comm_name + "','" + x.value + "')")
}
Jupyter.notebook.kernel.comm_manager.register_target(comm_name, function(comm, msg)
{
// comm is the frontend comm instance, msg is the comm_open message, which can carry data
// Register handlers for later messages:
comm.on_msg(function(msg) {
document.getElementById("out").value = msg.content.data;
});
//comm.on_close(function(msg) {...});
//comm.send({'foo': 40}); what is it??
});
</script>
<label for="in">Input:</label>
<input type="text" id="in" name="in" oninput="fcalc(this)">
<label for="out">Out:</label>
<input type="text" id="out">
"""
display(HTML(html))
https://stackoverflow.com/questions/32974051
复制相似问题