如何禁用python警告

2024-04-19 08:14:54 发布

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

我使用的代码使用^{}库抛出了很多(目前对我来说)无用的警告。阅读(/扫描)文档时,我只找到了一种方法to disable warnings for single functions。但我不想改变这么多代码。

是否有类似python -no-warning foo.py的标志?

你推荐什么?


Tags: to方法no代码文档py警告for
3条回答

你看过python文档的suppress warnings部分吗?

If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning using the catch_warnings context manager:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

我不宽恕,但您可以用以下命令来抑制所有警告:

import warnings
warnings.filterwarnings("ignore")

例如:

>>> import warnings
>>> def f():
...  print('before')
...  warnings.warn('you are warned!')
...  print('after')
>>> f()
before
__main__:3: UserWarning: you are warned!
after
>>> warnings.filterwarnings("ignore")
>>> f()
before
after

您还可以定义一个环境变量(2010年的新特性,即python 2.7)

export PYTHONWARNINGS="ignore"

测试如下:默认值

$ export PYTHONWARNINGS="default"
$ python
>>> import warnings
>>> warnings.warn('my warning')
__main__:1: UserWarning: my warning
>>>

忽略警告

$ export PYTHONWARNINGS="ignore"
$ python
>>> import warnings
>>> warnings.warn('my warning')
>>> 

对于不推荐警告,请查看how-to-ignore-deprecation-warnings-in-python

复制到这里。。。

^{} module的文档中:

 #!/usr/bin/env python -W ignore::DeprecationWarning

如果您在Windows上,请将-W ignore::DeprecationWarning作为参数传递给Python。不过最好是通过强制转换到int来解决问题。

(注意,在Python3.2中,默认情况下会忽略弃用警告。)

或:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=DeprecationWarning)
    import md5, sha

yourcode()

现在您仍然可以得到所有其他的DeprecationWarnings,但不是由以下原因引起的:

import md5, sha

这是-W option

python -W ignore foo.py

相关问题 更多 >