简体   繁体   English

如何禁用 Python 警告?

[英]How to disable Python warnings?

I am working with code that throws a lot of (for me at the moment) useless warnings using the warnings library.我正在处理使用warnings库抛出很多(目前对我而言)无用警告的代码。 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 a flag like python -no-warning foo.py ?python -no-warning foo.pypython -no-warning foo.py这样的标志?

What would you recommend?你会推荐什么?

Look at the Temporarily Suppressing Warnings section of the Python docs:查看 Python 文档的临时抑制警告部分:

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:如果您使用的代码知道会引发警告,例如已弃用的函数,但不想看到警告,则可以使用catch_warnings上下文管理器抑制警告:

 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
<stdin>:3: UserWarning: you are warned!
after
>>> warnings.filterwarnings("ignore")
>>> f()
before
after

-W选项

python -W ignore foo.py

You can also define an environment variable (new feature in 2010 - ie python 2.7)您还可以定义一个环境变量(2010 年的新功能 - 即 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对于弃用警告,请查看how-to-ignore-deprecation-warnings-in-python

Copied here...复制到这里...

From documentation of the warnings module :warnings模块的文档:

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

If you're on Windows: pass -W ignore::DeprecationWarning as an argument to Python.如果您使用的是 Windows:将-W ignore::DeprecationWarning作为参数传递给 Python。 Better though to resolve the issue, by casting to int .最好通过转换为int来解决问题。

(Note that in Python 3.2, deprecation warnings are ignored by default.) (请注意,在 Python 3.2 中,默认情况下会忽略弃用警告。)

Or:或者:

import warnings

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

yourcode()

Now you still get all the other DeprecationWarning s, but not the ones caused by:现在你仍然得到所有其他的DeprecationWarning s,但不是由以下原因引起的:

import md5, sha

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:这是一个老问题,但PEP 565中有一些更新的指南,如果您正在编写应该使用的 Python 应用程序,可以关闭所有警告:

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 .推荐这样做的原因是它默认关闭所有警告,但至关重要的是允许它们通过命令行上的python -WPYTHONWARNINGS

If you don't want something complicated, then:如果你不想要复杂的东西,那么:

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

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

Not to make it complicated, just use these two lines不要让它复杂,只需使用这两行

import warnings
warnings.filterwarnings('ignore')

When all else fails use this: https://github.com/polvoazul/shutup当所有其他方法都失败时,请使用: https : //github.com/polvoazul/shutup

pip install shutup

then add to the top of your code:然后添加到代码的顶部:

import shutup; shutup.please()

Disclaimer: I am the owner of that repository.免责声明:我是该存储库的所有者。 I wrote it after the 5th time I needed this and couldn't find anything simple that just worked.我在第 5 次需要它之后写了它,但找不到任何简单的东西。

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

Change ignore to default when working on the file or adding new functionality to re-enable warnings.在处理文件或添加新功能以重新启用警告时,将忽略更改为默认值。

I realise this is only applicable to a niche of the situations, but within a numpy context I really like using np.errstate :我意识到这仅适用于特定情况,但在numpy上下文中我真的很喜欢使用np.errstate

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

However, using np.errstate :但是,使用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.最好的部分是您只能将其应用于非常特定的代码行。


More pythonic way to ignore WARNINGS忽略警告的更多 Pythonic 方式


Since ' warning.filterwarnings() ' is not suppressing all the warnings, i will suggest you to use the following method:由于“ warning.filterwarnings() ”并未抑制所有警告,我建议您使用以下方法:

import logging
    
for name in logging.Logger.manager.loggerDict.keys():
    logging.getLogger(name).setLevel(logging.CRITICAL)

#rest of the code starts here...

OR,或者,

If you want to suppress only a specific set of warnings, then you can filter like this:如果你只想抑制一组特定的警告,那么你可以这样过滤:

import logging
    
for name in logging.Logger.manager.loggerDict.keys():
    if ('boto' in name) or ('urllib3' in name) or ('s3transfer' in name) or ('boto3' in name) or ('botocore' in name) or ('nose' in name):
            logging.getLogger(name).setLevel(logging.CRITICAL)

#rest of the code starts here...

You can use this code at the top of the main.py: 您可以在main.py的顶部使用以下代码:

def warn(*args, **kwargs):
    pass
import warnings
warnings.warn = warn

warnings are output via stderr and the simple solution is to append '2> /dev/null' to the CLI.警告通过 stderr 输出,简单的解决方案是将“2> /dev/null”附加到 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.这对许多用户来说很有意义,例如那些使用 python 2.6 依赖项(如 yum)并且各种模块在其覆盖范围内被推到灭绝边缘的 centos 6 用户。

this is especially true for cryptography involving SNI et cetera.对于涉及 SNI 等的密码学尤其如此。 one can update 2.6 for HTTPS handling using the proc at: https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl-py2可以使用以下 proc 更新 2.6 以进行 HTTPS 处理: 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.回应FriendFX。 sentence one (1) responds directly to the problem with an universal solution.句子一 (1) 直接以通用解决方案回应问题。 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.句子二 (2) 考虑到引用的锚重新“禁用警告”,这是特定于 python 2.6 的,并指出 RHEL/centos 6 用户不能直接使用 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" (ie, upgrade, backport, fix) python's HTTPS/TLS performance.尽管没有引用具体警告,但第二 (2) 段回答了我最常遇到的 2.6 问题,即密码学模块中的缺点以及如何“现代化”(即升级、向后移植、修复)python 的 HTTPS/TLS 性能. para three (3) merely explains the outcome of using the re-direct and upgrading the module/dependencies.第三段 (3) 仅解释了使用重定向和升级模块/依赖项的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM