Python程序中的警告控件
警告与程序中的错误不同。如果遇到错误,Python程序将立即终止。另一方面,警告并不致命。它显示某些消息,但程序继续。发出警告是为了警告用户某些并非完全例外的情况。通常,如果发现某些编程元素(例如关键字/函数/类等)已过时使用,则会出现警告。
警告消息通过warn()
Python标准库的“警告”模块中定义的函数显示。警告实际上是内置类层次结构中Exception的子类。有许多内置的警告子类。用户定义的子类也可以定义。
warn()
。警告示例
以下代码定义了一个具有不赞成使用的方法的类以及计划在该类的未来版本中禁止使用的方法。
# warningexample.py import warnings class WarnExample: def __init__(self): self.text = "Warning" def method1(self): warnings.warn( "method1 is deprecated, use new_method instead", DeprecationWarning ) print ('method1', len(self.text)) def method2(self): warnings.warn( "method2 will be deprecated in version 2, use new_method instead", PendingDeprecationWarning ) print ('method2', len(self.text)) def new_method(self): print ('new method', len(self.text)) if __name__=='__main__': e = WarnExample() e.method1() e.method2() e.new_method()
如果以上脚本是从命令提示符处执行的
E:\python37>python warningexample.py
终端上未显示警告消息。为此,您必须使用_Wd开关,如下所示
E:\python37>python -Wd warningexample.py warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead DeprecationWarning method1 7 warningexample.py:19: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead PendingDeprecationWarning method2 7 new method 7
同样,在交互式会话后也不会显示任何警告消息。
E:\python37>python >>> from warningexample import WarnExample >>> e = WarnExample()>>> e.method1() method1 7 >>> e.method2() method2 7 >>> e.new_method() new method 7
您必须使用–Wd开始Python会话
E:\python37>python -Wd >>> from warningexample import WarnExample >>> e=WarnExample() >>> e.method1() E:\python37\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead DeprecationWarning method1 7 >>> e.method2() E:\python37\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead PendingDeprecationWarning method2 7 >>> e.new_method() new method 7
警告过滤器
警告过滤器控制警告是被忽略,显示还是变成错误(引发异常)。
以下交互式会话将过滤器设置为默认simplefilter()
方法。
E:\python37>python >>> import warnings >>> warnings.simplefilter('default') >>> from warningexample import WarnExample >>> e=WarnExample() >>> e.method1() E:\python37\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead DeprecationWarning method1 7 >>> e.method2() E:\python37\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead PendingDeprecationWarning method2 7 >>> e.new_method() new method 7
为了暂时禁止警告,请将simplefilter设置为'ignore'。
import warnings def function(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(): warnings.simplefilter("ignore") function()