IPython - Run all cells below from a widget

后端 未结 3 1491
春和景丽
春和景丽 2020-12-25 15:27

I\'m trying use a multi select widget to enable users to select from a list of countries, and then have a widget button which, when clicked, runs all the cells below.

<
相关标签:
3条回答
  • 2020-12-25 15:46

    If I understood correctly you could do that via js.

    See the following code:

    from IPython.display import Javascript
    Javascript('IPython.notebook.execute_cells_below()')
    

    Will execute all the cells below the active cell so for you button it could be something like:

    from IPython.display import Javascript, display
    from ipywidgets import widgets
    
    def run_all(ev):
        display(Javascript('IPython.notebook.execute_cells_below()'))
    
    button = widgets.Button(description="Create next input")
    button.on_click(run_all)
    display(button)
    

    Let me know if this is what you need.

    0 讨论(0)
  • 2020-12-25 15:59

    To run all cells below the current cell without executing the cell that has this button:

    from IPython.display import Javascript, display
    from ipywidgets import widgets
    
    def run_all(ev):
        display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1, IPython.notebook.ncells())'))
    
    button = widgets.Button(description="Run all below")
    button.on_click(run_all)
    display(button)
    

    This allows the current cell to also prompt for other inputs and those input values to be preserved. IPython.notebook.execute_cells_below() will execute the current cell and if other inputs are also displayed in this cell they will get their default values.

    0 讨论(0)
  • 2020-12-25 16:01

    You've already received some excellent suggestions, but I'd just like to mention a pretty flexible option with HTML:

    Code:

    from IPython.core.display import HTML
    HTML('''<script> </script> <form action="javascript:IPython.notebook.execute_cells_below()"><input type="submit" id="toggleButton" value="Refresh"></form>''')
    

    This will produce a button for you that runs all cells below in the notebook

    A bonus feature with this approach is that the layout of your button will follow a theme selection if you're using Jupyter Themes from Dunovank on github https://github.com/dunovank/jupyter-themes

    I tried to attach a screenshot, but I can't do that yet.

    0 讨论(0)
提交回复
热议问题