【问题标题】:How to make a python command executed via Jupyter.kernel.execute command visible in an Input Cell in Jupyter Notebook如何使通过 Jupyter.kernel.execute 命令执行的 python 命令在 Jupyter Notebook 的输入单元中可见
【发布时间】:2016-06-13 06:39:54
【问题描述】:

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

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

【问题讨论】:

    标签: python kernel execute jupyter


    【解决方案1】:

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

    %%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 和一些东西可能会改变,也许上面发布的代码不是满足您需要的最佳方式。

    【讨论】:

    • 目前效果很好。干净整洁。你不使用 kernel.execute,至少是明确的。 cell.execute 可能正在隐式使用它。魔术是创建和选择下一个单元格。否则它可以工作但不显示。谢谢。
    猜你喜欢
    • 2018-06-01
    • 2019-07-13
    • 1970-01-01
    • 2021-11-25
    • 2019-08-20
    • 2018-12-12
    • 2016-12-06
    • 2016-09-06
    相关资源
    最近更新 更多