IPython notebook~用javascript运行python代码? [英] IPython notebook ~ Using javascript to run python code?

查看:323
本文介绍了IPython notebook~用javascript运行python代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图通过javascript直接执行python代码:

I am trying to execute python code through javascript directly:


  1. 我在Chrome上启动IPython Notebook

  2. 使用chrome开发者工具我打开javascript控制台。

在javascript consolde中,我输入: IPython.notebook.kernel.execute(2 + 2)

In the javascript consolde, I type: IPython.notebook.kernel.execute("2+2")

但我得到一个奇怪的输出:6CEA73CC644648DDA978FDD6A913E519

But I get a strange output: "6CEA73CC644648DDA978FDD6A913E519"

有没有办法利用所有可用的IPython javascript函数,从图像中描述的javascript控制台运行python代码?我确定有一种方法,但我一直在打它太久了,以为我会在这里发帖。

Is there any way to take advantage of all the IPython javascript functions available, to run python code from the javascript console as depicted in the image? I'm sure there's a way but I've been beating at it for way too long and thought I would post here.

(我需要这个来建立一个应用程序顶部的IPython)

(I need this to build an app on top of IPython)

提前致谢!

推荐答案

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

You can call Python code execution from JavaScript with Jupyter.notebook.kernel.execute() function.

依赖于此<来自Craig Dennis的href =https://gist.github.com/craigsdennis/ddfaa99a6291f05fef879329821872ee =nofollow noreferrer> gist 您可以在Jupyter单元格中插入此代码并运行它

Depend on this gist from Craig Dennis you can insert this code in Jupyter cell and run it

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

Result would be output to browser javascript console.

这篇关于IPython notebook~用javascript运行python代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆