IPython notebook ~ Using javascript to run python code?

此生再无相见时 提交于 2020-01-02 06:08:54

问题


I am trying to execute python code through javascript directly:

  1. I fire up IPython Notebook on Chrome
  2. Using chrome developer tools I open up the javascript console.

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

But I get a strange output: "6CEA73CC644648DDA978FDD6A913E519"

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.

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

Thanks in advance!


回答1:


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

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

Result would be output to browser javascript console.




回答2:


Are you aware of this blogpost? http://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/

I think the exact way he uses doesn't work anymore, but maybe it can get you a step forward



来源:https://stackoverflow.com/questions/32974051/ipython-notebook-using-javascript-to-run-python-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!