如何禁用python警告

问题:如何禁用python警告

我正在使用的代码会使用该warnings库抛出很多(目前对我来说)无用的警告。阅读(/扫描)文档后,我只找到了一种禁用单个功能警告的方法。但是我不想更改太多代码。

可能有像这样的标志python -no-warning foo.py吗?

你会推荐什么?

I am working with code that throws a lot of (for me at the moment) useless warnings using the warnings library. Reading (/scanning) the documentation I only found a way to disable warnings for single functions. But I don’t want to change so much of the code.

Is there maybe a flag like python -no-warning foo.py?

What would you recommend?


回答 0

-W选项

python -W ignore foo.py

There’s the -W option.

python -W ignore foo.py


回答 1

您是否查看了python文档的“ 抑制警告”部分?

如果您使用的代码知道会发出警告(例如已弃用的函数),但又不想看到该警告,则可以使用catch_warnings上下文管理器来抑制该警告:

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

Did you look at the suppress warnings section of the python docs?

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()

I don’t condone it, but you could just suppress all warnings with this:

import warnings
warnings.filterwarnings("ignore")

Ex:

>>> 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

回答 2

您还可以定义环境变量(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')
>>> 

对于弃用警告,请查看如何忽略python中的弃用警告

在这里复制…

warnings模块的文档中:

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

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

(请注意,在Python 3.2中,默认情况下会忽略弃用警告。)

要么:

import warnings

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

yourcode()

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

import md5, sha

You can also define an environment variable (new feature in 2010 – i.e. python 2.7)

export PYTHONWARNINGS="ignore"

Test like this: Default

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

Ignore warnings

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

For deprecation warnings have a look at how-to-ignore-deprecation-warnings-in-python

Copied here…

From documentation of the warnings module:

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

If you’re on Windows: pass -W ignore::DeprecationWarning as an argument to Python. Better though to resolve the issue, by casting to int.

(Note that in Python 3.2, deprecation warnings are ignored by default.)

Or:

import warnings

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

yourcode()

Now you still get all the other DeprecationWarnings, but not the ones caused by:

import md5, sha

回答 3

这是一个老问题,但是PEP 565中有一些较新的指南,如果您正在编写python应用程序,则应关闭所有警告,请使用:

import sys
import warnings

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

推荐这样做的原因是默认情况下它会关闭所有警告,但至关重要的是允许通过python -W命令行或再次将其打开PYTHONWARNINGS

This is an old question but there is some newer guidance in PEP 565 that to turn off all warnings if you’re writing a python application you should use:

import sys
import warnings

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

The reason this is recommended is that it turns off all warnings by default but crucially allows them to be switched back on via python -W on the command line or PYTHONWARNINGS.


回答 4

如果您不想要复杂的东西,那么:

import warnings
warnings.filterwarnings("ignore", category=FutureWarning)

If you don’t want something complicated, then:

import warnings
warnings.filterwarnings("ignore", category=FutureWarning)

回答 5

如果您知道通常会遇到什么无用的警告,则可以按消息过滤它们。

import warnings

#ignore by message
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")

#part of the message is also okay
warnings.filterwarnings("ignore", message="divide by zero encountered") 
warnings.filterwarnings("ignore", message="invalid value encountered")

If you know what are the useless warnings you usually encounter, you can filter them by message.

import warnings

#ignore by message
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")

#part of the message is also okay
warnings.filterwarnings("ignore", message="divide by zero encountered") 
warnings.filterwarnings("ignore", message="invalid value encountered")

回答 6

我意识到这仅适用于特定情况,但是在numpy上下文中我真的很喜欢使用np.errstate

np.sqrt(-1)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
nan

但是,使用np.errstate

with np.errstate(invalid='ignore'):
    np.sqrt(-1)
nan

最好的部分是您可以将其仅应用于非常特定的代码行。

I realise this is only applicable to a niche of the situations, but within a numpy context I really like using np.errstate:

np.sqrt(-1)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
nan

However, using np.errstate:

with np.errstate(invalid='ignore'):
    np.sqrt(-1)
nan

The best part being you can apply this to very specific lines of code only.


回答 7

警告通过stderr输出,简单的解决方案是将’2> / dev / null’附加到CLI。对于许多用户来说,这很有意义,例如那些使用python 2.6依赖项(例如yum)的centos 6的用户,并且各种模块都被推到了灭绝的边缘。

对于涉及SNI等的密码学尤其如此。一个人可以使用以下过程中的proc更新2.6以进行HTTPS处理:https : //urllib3.readthedocs.io/en/latest/user-guide.html#ssl-py2

警告仍然存在,但是您想要的所有内容都已反向移植。尽管stdout内容本身不会更改,但stderr的重定向将使您获得干净的终端/外壳输出。

回应FriendFX。句子(1)用通用解决方案直接回答了这个问题。句子二(2)考虑到了python 2.6特定的引用的anchor re“ disable warnings”,并指出RHEL / centos 6用户不能直接使用2.6。尽管未引用任何具体的警告,但第二(2)款回答了我最经常得到的2.6问题,即密码模块中的缺点以及如何“现代化”(即升级,反向移植,修复)python的HTTPS / TLS性能。第三(3)段仅说明使用重定向和升级模块/依赖项的结果。

warnings are output via stderr and the simple solution is to append ‘2> /dev/null’ to the CLI. this makes a lot of sense to many users such as those with centos 6 that are stuck with python 2.6 dependencies (like yum) and various modules are being pushed to the edge of extinction in their coverage.

this is especially true for cryptography involving SNI et cetera. one can update 2.6 for HTTPS handling using the proc at: https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl-py2

the warning is still in place, but everything you want is back-ported. the re-direct of stderr will leave you with clean terminal/shell output although the stdout content itself does not change.

responding to FriendFX. sentence one (1) responds directly to the problem with an universal solution. sentence two (2) takes into account the cited anchor re ‘disable warnings’ which is python 2.6 specific and notes that RHEL/centos 6 users cannot directly do without 2.6. although no specific warnings were cited, para two (2) answers the 2.6 question I most frequently get re the short-comings in the cryptography module and how one can “modernize” (i.e., upgrade, backport, fix) python’s HTTPS/TLS performance. para three (3) merely explains the outcome of using the re-direct and upgrading the module/dependencies.