您的位置:首页 > 编程语言 > Python开发

python - warnings

2014-03-04 19:41 134 查看

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()

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: