zoukankan      html  css  js  c++  java
  • Python&R:警告信息管理

    计算机程序有时很人性化,比如给你警告提示信息;

    计算机程序有时又非常不人性化,比如动不动就给你警告提示......

    如果你的程序是要给客户使用,有运行美化要求;

    再尤其是比如警告出现在循环里的情况,那么每次循环都要打印出一堆警告信息......那就十分扯淡了。

    怎么办?

    显然,警告(Warning)并不是错误(Error),程序并不会因警告的出现而中止运行。

    那些原始开发者一定早已考虑到这一点,设置了可供调整的警告输出模式。

    我们以Python和R为例,看看基本的警告信息管理操作。

    (一)Python

    我们编写以下程序:

    import warnings as w
    if 1==1:
        w.warn('警告!!!')

    运行结果为:

    Warning (from warnings module):
      File "D:/warnings.py", line 3
        w.warn('警告!!!')
    UserWarning: 警告!!!

    1)当使用命令行模式执行程序时,可在执行命令里加入-W ignore:

    python -W ignore XXX.py

    此时运行结果不输出警告。

    2)也可在程序中导入warnings模块,使用警告过滤器。

    import warnings as w
    w.filterwarnings("ignore")
    if 1==1:
        w.warn('警告!!!')

    此时运行结果也不输出警告。

    而事实上,还有其它几个参数可供选择以控制警告:

    Value

    Disposition

    "error"

    turn matching warnings into exceptions

    "ignore"

    never print matching warnings

    "always"

    always print matching warnings

    "default"

    print the first occurrence of matching warnings for each location where the warning is issued

    "module"

    print the first occurrence of matching warnings for each module where the warning is issued

    "once"

    print only the first occurrence of matching warnings, regardless of location

    如将程序改为:

    import warnings as w
    w.filterwarnings("ignore")
    if 1==1:
        w.warn('警告!!!')
    w.filterwarnings("always")
    if 1==1:
        w.warn('警告!!!---')
    w.filterwarnings("error")
    if 1==1:
        w.warn('警告!!!---===')
    print('sfsdfsfsdfsdf')

    输出结果:

    Warning (from warnings module):
      File "D:/warnings.py", line 7
        w.warn('警告!!!---')
    UserWarning: 警告!!!---
    Traceback (most recent call last):
      File "D:/warnings.py", line 10, in <module>
        w.warn('警告!!!---===')
    UserWarning: 警告!!!---===

    (二)R

    R语言控制警告就更方便了。可在程序前插入命令:

    options(warn=N)

    其中,N的取值可以为负数、0、1、2。

    warn = 负数,则所有warning message都被忽略。
    warn = 0 (默认值),则所有warning messages会被储存起来直到上级函数运行结束。
    warn = 1,则一旦产生warning message,这条信息会被立即显示出来。
    warn = 2 或更大的数值, 则warning message会被立即显示并转换成error message。

    参考资料:

    https://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings

    https://blog.csdn.net/xiaodongxiexie/article/details/65646239

    https://blog.csdn.net/stat_elliott/article/details/37878247

  • 相关阅读:
    selenium之WebDriver API
    python开发之面试题
    python开发之协程
    Python爬虫
    Python基础
    Django-搭建win7虚拟环境-virtualenv
    Linux系列
    Python知识点
    Python知识点
    Python基础-生物信息:找出基因,生物学家使用字母A、C、T和G构成的字符串建模一个基因组。
  • 原文地址:https://www.cnblogs.com/maoerbao/p/11849714.html
Copyright © 2011-2022 走看看