jupyter笔记本:如何以编程方式停止单元执行,同时继续运行后续单元

use*_*206 6 python jupyter jupyter-notebook

我想以编程方式跳过在 jupyter 笔记本的单元格中执行一些代码,而不将所有内容包装在 if-else 块中。

到目前为止,我从这个问题中找到的最接近的解决方案:/sf/answers/3986717381/是这样的:

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

raise StopExecution
Run Code Online (Sandbox Code Playgroud)

但是,它会停止当前单元格的执行以及所有后续单元格的执行,而我只想提前退出当前单元格。有没有办法继续执行其他单元格?

这是一个代码示例:

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

render_some_output()
Run Code Online (Sandbox Code Playgroud)

如果stop_cell()被调用,我不想render_some_output()执行,而是整体执行笔记本执行。

pgc*_*ahy 0

我知道您不想使用大量 if else 语句,但我认为最简单的解决方案是global_run_flag = False在每个可选代码块之前有一个带有 and then 的单元格,只需在其前面添加if not global_run_flag:then 当您将 the 设置global_run_flag为 True 时,它​​将跳过所有包装代码块的执行。