jupyter:如何停止执行错误?

jupyter: how to stop execution on errors?

在 python 中防御性中止执行的常见方法是简单地执行以下操作:

if something_went_wrong:
    print("Error message: goodbye cruel world")
    exit(1)

但是,在使用 jupyter notebook 时,这不是一个好的做法,因为这似乎会完全中止内核,这并不总是需要的。除了 hack-y inifinte 循环之外,jupyter 中还有 proper/better 方式吗?

不,exit() 通常 不是 中止 Python 执行的方式。 exit() 意味着用状态码立即停止解释器。

通常,您会编写这样的脚本:

 if __name__ == '__main__':
     sys.exit(main())

尽量不要将 sys.exit() 放在代码中间——这是不好的做法, 你最终可能会得到非关闭的文件句柄或锁定的资源。

要执行您想要的操作,只需引发正确类型的异常。如果它传播到 eval 循环,IPython 将停止笔记本执行。

此外,它还会为您提供有用的错误消息和堆栈跟踪。

if type(age) is not int:
    raise TypeError("Age must be an integer")
elif age < 0:
    raise ValueError("Sorry you can't be born in the future")
else :
    ...

您甚至可以使用 %debug 检查堆栈 post-mortem 以查看哪里出了问题,但这是另一个主题。