如何通过Jupyter Notebook

时间:2016-06-13 06:39:54

标签: python kernel execute jupyter

我可以通过Jupyter.kernel.execute(命令)从Javascript端执行python命令。例如,命令可能类似于" a = 3"。我可以看到一个名为" a"的新变量。设置为3,即可。

我想让这个命令在INPUT CELL中回显,好像它是手动输入的一样。是否有可能,怎么办呢?

1 个答案:

答案 0 :(得分:2)

一个非常简单的例子是(将下面的代码粘贴到笔记本单元格中):

%%javascript

// Function that accepts a string of code
var create_and_execute_cell_below = function (code){
    var nb = Jupyter.notebook

    // create cell below this one
    nb.insert_cell_below()

    // select cell below (the one we have created)
    var cell = nb.select_next().get_selected_cell()

    // set text in the cell
    cell.set_text(code)

    // execute cell
    cell.execute()
}

// run the function created above with code 'k = 1'
// and it will create a new cell, filled with 'k = 1'
// and it will execute that cell.
// if you run this cell using [ctrl] + [enter] only one cell
// will be created.
// if you run this cell using [Shift] + [enter] two cells
// will be created, the one of the [Shift] + [enter] command
// and the one of the function created above with the code.
create_and_execute_cell_below('k = 1')

我希望它有所帮助。

OTOH,the front-end API could be not very stable and there is a lack of documentation以及其他一些内容可能会发生变化,上面发布的代码可能不是您做所需的最佳方式。