如何防止警告在消息末尾打印奇怪的文本?

2024-04-19 10:39:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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]

Tags: importtruereturniffooisdefmsg
1条回答
网友
1楼 · 发布于 2024-04-19 10:39:59

有一种方法:

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.

相关问题 更多 >