IPython笔记本 ~ 使用JavaScript运行Python代码?

11

我正在尝试通过JavaScript直接执行Python代码:

  1. 我在Chrome上启动了IPython Notebook
  2. 使用Chrome开发者工具,我打开了javascript控制台。

在javascript控制台中,我键入:IPython.notebook.kernel.execute("2+2")

enter image description here

但是我得到了奇怪的输出:"6CEA73CC644648DDA978FDD6A913E519"

是否有任何方法可以利用所有可用的IPython javascript函数,在javascript控制台中运行Python代码,如图所示?我确定有一种方法,但我已经试了很长时间,所以想在这里发布。

(我需要这个来构建一个基于IPython的应用程序)

提前感谢您!

4个回答

6

你可以使用 Jupyter.notebook.kernel.execute() 函数从 JavaScript 调用 Python 代码执行。

依赖于 Craig Dennis 的 gist,您可以在 Jupyter 单元格中插入此代码并运行它。

%%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控制台。


为了将大型数据框传输到JavaScript,可能需要关闭pandas的预览功能:使用pandas.option_context("display.max_rows", None, "display.max_columns", None, "display.width", None): print(dataFrame)另请参见https://dev59.com/oWIk5IYBdhLWcg3wl_PE - Stefan

1

1
谢谢,是的,我尝试了那个,在评论中有一个IPython 2.0和3.1的解决方案,但我无法让任何解决方案与IPython 4.0.0一起使用(也尝试了一些解决方案但没有成功)。 - applecider
也许可以在Jupyter存储库的GitHub问题中提问。以这种方式获得帮助是不错的经验。 - arthaigo
谢谢你的建议,我会试一试。 - applecider

1

经过两天的努力,我找到了解决方案。

为了运行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))

0
为隔离出一个最小可行的实现,我采用了与ChrCury78基本相同的方法,在仅几个步骤内就能从IPython内核获取响应。
由于我想在Javascript中使用从Python返回的数据,在这些示例中,我只是将消息内容存储在console的成员中。(不像ChrCury78那样,他把结果推到笔记本单元格的输出中)。在我的真正扩展中,我可能会将它附加到Jupyter上的名称或我自己创建的对象上。
>> Jupyter.notebook.kernel.comm_manager.register_target("mycomm", (comm, msg) => {comm.on_msg( m => {console.retval = m.content.data})})
<- undefined
>> Jupyter.notebook.kernel.execute("from ipykernel.comm import Comm; Comm(target_name='mycomm').send('FOO')")
<- "{hex UID}"
>> console.retval
<- "FOO"

多行Python代码也很好运行,而且既然我已经导入了Comm,就不需要再次导入它了。
>> Jupyter.notebook.kernel.execute("l = []\nfor x in range(5):\n  l.append(x)\nComm(target_name='mycomm').send(l)")
<- "{hex UID}"
>> console.retval
<- Array(5) [ 0, 1, 2, 3, 4 ]

如果您想在之后保持内核命名空间的清洁,可以在 Python 命令的末尾添加 del Comm

我一定会为这两个操作编写某种包装函数。


这是使用 Python 3.9.11 和以下已安装的软件包:

ipykernel                         6.9.2
ipython                           8.1.1
ipython-genutils                  0.2.0
ipywidgets                        7.7.0

jupyter                           1.0.0
jupyter-client                    7.1.2
jupyter-console                   6.4.3
jupyter-contrib-core              0.3.3
jupyter-contrib-nbextensions      0.5.1
jupyter-core                      4.9.2
jupyter-highlight-selected-word   0.2.0
jupyter-latex-envs                1.4.6
jupyter-nbextensions-configurator 0.4.1
jupyterlab-pygments               0.1.2
jupyterlab-widgets                1.1.0


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接