Warnings 核心功能 |
warnings.WarningMessage |
Class | Description |
---|---|
This is the base class of all warning category classes. It isa subclass of Exception. | |
The default category for warn(). | |
Base category for warnings about deprecated features (ignoredby default). | |
Base category for warnings about dubious syntactic features. | |
Base category for warnings about dubious runtime features. | |
Base category for warnings about constructs that will changesemantically in the future. | |
Base category for warnings about features that will bedeprecated in the future (ignored by default). | |
Base category for warnings triggered during the process ofimporting a module (ignored by default). | |
Base category for warnings related to Unicode. |
产生警告 |
warnings.warn(message[,category[,stacklevel]]) |
message, 警告消息内容 |
category, 警告消息类型 |
stacklevel, 主要被Python中的封装函数使用,例如:
def deprecation(message): warnings.warn(message, DeprecationWarning, stacklevel=2) |
import warnings |
过滤警告 |
warnings.filterwarnings(action[,message[,category[,module[,lineno[,append]]]]]) warnings.simplefilter(action[,category[,lineno[,append]]]) |
action, 可选值如下: error, 将异常变为错误 ignore, 忽略警告 always, 持续警告 default, 输出每个位置的第一次警告 module, 输出模块的第一次警告 once, 警告一次,不考虑位置 |
message, 警告文本消息 |
category, 警告类型 |
module, 模块名 |
lineno, 产生警告的行号 |
append, 附属在末尾 |
import warnings
warnings.simplefilter('ignore') |
例子 |
#!/usr/bin/env python # -*- coding: utf8 -*- import logging import warnings logging.basicConfig(level=logging.INFO) def filterwarn(): # warnings.simplefilter('ignore', UserWarning) # advance warnings flter function warnings.filterwarnings('ignore', '.*warn.*', UserWarning, 'module') def main(): filterwarn() # compare the two following items. warnings.warn("This is a warning message.") logging.warn("[+] This is a warn message.") logging.info("[+] This is a info message.") if __name__ == "__main__": main() |