IPython - Run all cells below from a widget

会有一股神秘感。 提交于 2019-11-29 00:49:07

问题


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.

This displays the list.

from IPython.display import display
w = widgets.SelectMultiple(

    description="Select up to five countries",
    options=dfCountries['name'].tolist()   
)
display(w)

And I want something like this to run all cells below:

def run_all(button):
    get_ipython().run_cell()

button = widgets.Button(description="Create next input")
button.on_click(run_all)
display(button)

But I can't find the hook to 'run all cells below

Thanks


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/32714783/ipython-run-all-cells-below-from-a-widget

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