mirror of
https://github.com/apachecn/ailearning.git
synced 2026-02-10 05:45:40 +08:00
52 lines
952 B
Markdown
52 lines
952 B
Markdown
# 警告
|
||
|
||
出现了一些需要让用户知道的问题,但又不想停止程序,这时候我们可以使用警告:
|
||
|
||
首先导入警告模块:
|
||
|
||
In [1]:
|
||
|
||
```py
|
||
import warnings
|
||
|
||
```
|
||
|
||
在需要的地方,我们使用 `warnings` 中的 `warn` 函数:
|
||
|
||
```py
|
||
warn(msg, WarningType = UserWarning)
|
||
```
|
||
|
||
In [2]:
|
||
|
||
```py
|
||
def month_warning(m):
|
||
if not 1<= m <= 12:
|
||
msg = "month (%d) is not between 1 and 12" % m
|
||
warnings.warn(msg, RuntimeWarning)
|
||
|
||
month_warning(13)
|
||
|
||
```
|
||
|
||
```py
|
||
c:\Anaconda\lib\site-packages\IPython\kernel\__main__.py:4: RuntimeWarning: month (13) is not between 1 and 12
|
||
|
||
```
|
||
|
||
有时候我们想要忽略特定类型的警告,可以使用 `warnings` 的 `filterwarnings` 函数:
|
||
|
||
```py
|
||
filterwarnings(action, category)
|
||
```
|
||
|
||
将 `action` 设置为 `'ignore'` 便可以忽略特定类型的警告:
|
||
|
||
In [3]:
|
||
|
||
```py
|
||
warnings.filterwarnings(action = 'ignore', category = RuntimeWarning)
|
||
|
||
month_warning(13)
|
||
|
||
``` |