Issue
I am creating a widget that will execute only certain cells in the notebook--to generate new plots based upon changed data. While Jupyter can do things like execute all cells in the notebook, or execute all cells below the current cell, etc.
Instead, I wanted to create tags for the cells that I want to selectively execute. Then when I push the button I can execute this code and run the cells.
The widget code itself is not important--that part is easy. The harder thing is to figure out how to implement the communication between python and javascript within the notebook. Anyone have any ideas.
Solution
So I figured this out. I think other folks have been looking for a answer similar to this, so I am posting it.
First, I had to tag the relevant cells in the notebook. You can do that through the "View", and then "Cell Toolbar" in the notebook.
Second, create a code cell with these functions. The first function will get all cells that have a certain tag. The second cell will run all cells that have that tag. In my case, the tagname was 'plotcell', but this can be changed to anything. This cell needs to run before trying to use this function, so I usually make it an initialization cell.
%%javascript
window.findCellIndicesByTag = function findCellIndicesByTag(tagName) {
return (Jupyter.notebook.get_cells()
.filter(
({metadata: {tags}}) => tags && tags.includes(tagName)
)
.map((cell) => Jupyter.notebook.find_cell_index(cell))
);
};
window.runPlotCells = function runPlotCells() {
var c = window.findCellIndicesByTag('plotcell');
Jupyter.notebook.execute_cells(c);
};
Finally, to run this code, you need to use the following code:
from IPython.core.display import Javascript
from IPython.display import display
def runPlotCells():
display(Javascript("window.runPlotCells()"))
This code will execute the previously created Javascript function to runPlotCells. I used the display
function so that the output in the notebook is suppressed and the results are visible in the browser developer console.
You then run this function after the on_click event from the button.
And that should be it.
Answered By - krishnab
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.