一旦满足条件如何停止python程序(在jupyter笔记本中)

Art*_*Sbr 6 python jupyter-notebook

我想知道 Jupyter Notebook 是否有一个命令,可以在发出命令后停止后续单元格的运行。

I found this question and tried sys.exit() but some of the cells below the command are still being executed.

The structure of my script looks as follows:

# tons of cells above
Run Code Online (Sandbox Code Playgroud)
if df["target"].mean() == 1:
    sys.exit("Condition met. Do not execute the cells below.")
Run Code Online (Sandbox Code Playgroud)
# tons of cells below
Run Code Online (Sandbox Code Playgroud)

Ideally, none of the cells represented by tons of cells below should be executed if df["target"].mean() is 1. Otherwise, I do want to the subsequent cells executed.

I suppose one solution would be to write the code of all the subsequent cells in an else statement inside the same cell where sys.exit() is written. However, I do not want to do this.

小智 8

尝试这个而不是sys.exit()

raise SystemExit("Stop right there!")
Run Code Online (Sandbox Code Playgroud)