jupyter notebook: how to stop cell execution programmatically while continuing running subsequent cells

Viewed 2200

I would like to skip executing some code in cells of a jupyter notebook programmatically without wrapping everything in if-else blocks.

The closest solution I found so far from this SO question: https://stackoverflow.com/a/56953105/3124206 is this:

class StopExecution(Exception):
    def _render_traceback_(self):
        pass

raise StopExecution

However, it stops both current cell execution as well all of the subsequent ones while I only want an early exit from the current cell. Is there a way to continue execution of other cells?

Here is a code sample:

if skip_page:
    display(HTML('<!--SKIP-PAGE-->'))
    stop_cell()

render_some_output()

In case stop_cell() is called, I would like render_some_output() not to execute but the notebook execution to carry on overall.

1 Answers

I know you don't want to use a lot of if else statements, but I think the simplest solution is to have one cell with global_run_flag = False and then before each optional code block, just preface it with if not global_run_flag: Then when you turn the global_run_flag to True, it will skip execution of all the wrapped code blocks.

Related