14.11 输出警告信�¶

问题¶

你希望自己的程�能生�警告信�(比如废弃特性或使用问题)。

解决方案¶

�输出一个警告消�,�使用 warning.warn() 函数。例如:

import warnings

def func(x, y, logfile=None, debug=False):
    if logfile is not None:
         warnings.warn('logfile argument deprecated', DeprecationWarning)
    ...

warn() 的�数是一个警告消�和一个警告类,警告类有如下几�:UserWarning, DeprecationWarning, SyntaxWarning, RuntimeWarning, ResourceWarning, 或 FutureWarning.

对警告的处��决于你如何�行解释器以�一些其他�置。 例如,如果你使用 -W all 选项去�行Python,你会得到如下的输出:

bash % python3 -W all example.py
example.py:5: DeprecationWarning: logfile argument is deprecated
  warnings.warn('logfile argument is deprecated', DeprecationWarning)

通常�讲,警告会输出到标准错误上。如果你想讲警告转�为异常,�以使用 -W error 选项:

bash % python3 -W error example.py
Traceback (most recent call last):
  File "example.py", line 10, in <module>
    func(2, 3, logfile='log.txt')
  File "example.py", line 5, in func
    warnings.warn('logfile argument is deprecated', DeprecationWarning)
DeprecationWarning: logfile argument is deprecated
bash %

讨论¶

在你维护软件,�示用户�些信�,但是��需�将其上�为异常级别,那么输出警告信�就会很有用了。 例如,�设你准备修改�个函数库或框架的功能,你�以先为你�更改的部分输出警告信�,�时��兼容一段时间。 你还�以警告用户一些对代�有问题的使用方�。

作为�外一个内置函数库的警告使用例�,下�演示了一个没有关闭文件就销�它时产生的警告消�:

>>> import warnings
>>> warnings.simplefilter('always')
>>> f = open('/etc/passwd')
>>> del f
__main__:1: ResourceWarning: unclosed file <_io.TextIOWrapper name='/etc/passwd'
 mode='r' encoding='UTF-8'>
>>>

默认情况下,并�是所有警告消�都会出现。-W 选项能控制警告消�的输出。 -W all 会输出所有警告消�,-W ignore 忽略掉所有警告,-W error 将警告转��异常。 �外一�选择,你还�以使用 warnings.simplefilter() 函数控制输出。 always �数会让所有警告消�出现,`ignore 忽略调所有的警告,error 将警告转��异常。

对于简�的生�警告消�的情况这些已�足够了。 warnings 模�对过滤和警告消�处��供了大�的更高级的�置选项。 更多信�请�考 Python文档