python - warnings

Warnings 核心功能

warnings.WarningMessage
warnings.catch_warnings
warnings.default_action
warnings.defaultaction
warnings.filters
warnings.filterwarnings
warnings.formatwarning
warnings.linecache
warnings.once_registry
warnings.onceregistry
warnings.resetwarnings
warnings.showwarning
warnings.simplefilter
warnings.sys
warnings.types
warnings.warn
warnings.warn_explicit
warnings.warnpy3k


Class

Description

Warning

This is the base class of all warning category classes. It isa subclass of Exception.

UserWarning

The default category for warn().

DeprecationWarning

Base category for warnings about deprecated features (ignoredby default).

SyntaxWarning

Base category for warnings about dubious syntactic features.

RuntimeWarning

Base category for warnings about dubious runtime features.

FutureWarning

Base category for warnings about constructs that will changesemantically in the future.

PendingDeprecationWarning

Base category for warnings about features that will bedeprecated in the future (ignored by default).

ImportWarning

Base category for warnings triggered during the process ofimporting a module (ignored by default).

UnicodeWarning

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.warn('AAAAAAA',Warning)
warnings.warn('BBBBBBB',DeprecationWarning)
warnings.warn('CCCCCCC', UserWarning)


过滤警告

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')
warnings.simplefilter('ignore',UserWarning)
warnings.filterwarnings('ignore', '.*Warning.*',UserWarning, 'warnings', 12)


例子

#!/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()


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值