简体   繁体   English

针对 Jupyter Notebooks 的 Python 包中的错误处理

[英]Error handling in a Python Package aimed at Jupyter Notebooks

I am developing a Python package for use in Jupyter Notebooks.我正在开发一个用于 Jupyter Notebooks 的 Python 包。 It will also be accessed via python module scripts but the Jupyter Notebook is an interface I am targetting.它也可以通过 python 模块脚本访问,但 Jupyter Notebook 是我的目标接口。 However the handling of errors is very ugly within Jupyter notebooks as there is no simple way to set up a try-catch mechanism within each cell.然而,在 Jupyter Notebook 中错误的处理非常难看,因为没有简单的方法可以在每个单元中设置 try-catch 机制。

I am therefore thinking of replacing all of my exception-raising with a simple print statement for Jupyter notebooks but with standard exceptions for non-Jupyter environments such as Spyder.因此,我正在考虑用 Jupyter 笔记本的简单打印语句替换我所有的异常引发,但使用非 Jupyter 环境(如 Spyder)的标准异常。 To do this I will need to set some global variable within the Python package, which is do-able.为此,我需要在 Python 包中设置一些全局变量,这是可行的。 So the user simply gets a polite error rather than a listing with a Python error report showing the culprit line.所以用户只会得到一个礼貌的错误,而不是一个带有显示罪魁祸首行的 Python 错误报告的列表。

Does anyone have any suggestions for a better approach ?有没有人对更好的方法有任何建议?

May be have a look at the warning package.可以看看警告包。

import warnings

warnings.warn("deprecated", DeprecationWarning)

It also supports other warning types like Runtimewarning , Futurewarning etc..它还支持其他警告类型,如RuntimewarningFuturewarning等。

https://docs.python.org/3/library/warnings.html https://docs.python.org/3/library/warnings.html

Edit You can have exception hook and limit the traceback and instead print warnings using warnings package.编辑您可以使用异常挂钩并限制回溯,而是使用warnings包打印警告。

Refer to this StackOverflow post Hide traceback unless a debug flag is set请参阅此 StackOverflow 帖子隐藏回溯,除非设置了调试标志

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM