控制warning信息在控制台的显示

在运行代码时,有时出现warning信息,

1.当你后台不需要warning信息的时候,可以直接把warning信息省略掉。

2.如果代码是循环,则会在控制台打印多次warning信息,这会使得warning信息占满整个控制台,失去了有效的历史记录。

1.warning的地位

BaseException
 +-- Exception
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

2.警告过滤器与简易警告过滤器

对于这种情况,python有一个标准模块warnings,可以利用这个模块对warning信息进行过滤和处理。

def filterwarnings(action, message="", category=Warning, module="", lineno=0,
                   append=False):

警告过滤器用于控制警告的行为,如忽略,显示或转换为错误(引发异常)

警告过滤器维护着一个有序的过滤规则列表,匹配规则用于确定如何处理警告,任何特定警告都将依次与列表中的每个过滤规则匹配,直到找到匹配为止。

过滤规则类型为一个元组 (action,message,category,module,lineno),其中:

 The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception)

import warnings
warnings.filterwarnings(action='xxx')

  • message 是包含正则表达式的字符串,警告消息的开始必须匹配,不区分大小写
  • category 是一个警告类型(必须是 Warning 的子类)
  • module 是包含模块名称的正则表达式字符串,区分大小写
  • lineno 是一个整数,警告发生的行号,为 0 则匹配所有行号
warnings.filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)
  Insert an entry into the list of warnings filter specifications. 
  The entry
is inserted at the front by default; if append is true, it is inserted at the end.
  This checks the types of the arguments, compiles the message and module regular expressions, and inserts them as a tuple in the list of warnings filters.
  Entries closer to the front of the list override entries later in the list, if both match a particular warning. Omitted arguments default to a value that matches everything. warnings.simplefilter(action, category=Warning, lineno=0, append=False)   Insert a simple entry into the list of warnings filter specifications.
  The meaning of the function parameters
is as for filterwarnings(),
  but regular expressions are not needed as the filter inserted always matches any message in any module as long as the category and line number match.
原文地址:https://www.cnblogs.com/wqbin/p/11975860.html