python - 我们如何防止警告在其消息末尾打印奇怪的文本?

标签 python python-3.x exception error-handling warnings

<分区>

以下导致打印一些额外的奇怪输出

import warnings

def foo(x):

    if x > 100:
        msg = "Warning! x is big!"
        warnings.warn(msg)
    return True

foo(999999)

不仅仅是打印:

UserWarning: Warning! x is big!

我们得到:

UserWarning: Warning! x is big!
   warnings.warn(msg)

有时我什至得到:

UserWarning: Warning! x is big!
   ValueError [blah, blah, blah]

最佳答案

这是一种方法:

import warnings
import sys

if not sys.warnoptions:
    warnings.simplefilter("ignore")

def foo(x):

    if x > 100:
        msg = "Warning! x is big!"
        warnings.warn(msg)
    return True

foo(999999)

免责声明

Python documentation建议不要更改此设置:

sys.warnoptions

This is an implementation detail of the warnings framework; do not modify this value. Refer to the warnings module for more information on the warnings framework.

关于python - 我们如何防止警告在其消息末尾打印奇怪的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49015001/

相关文章:

Python/Fabric 的误解

python - UserWarning : Matplotlib is currently using agg, 所以无法显示数字

python - pandas groupby 计数、总和和平均值

java - 在异常处理程序中将数据保存到数据库 - Spring

python - 用正则表达式去除标点符号 - python

python - 使用 groupby+apply 对每个组进行聚类 - 性能问题

Python Pandas : output dataframe to csv with integers

python-3.x - 如何对列进行 groupby() 并按组迭代 sum()

java - 输入不匹配异常是什么意思?

java - 检查字段是否为空