繁体   English   中英

如何使用 warnings.filterwarnings 抑制第三方警告

[英]How to suppress a third-party warning using warnings.filterwarnings

我在我的 python 代码中使用 Paramiko(用于 sftp)。 一切正常,除了每次我导入或调用 paramiko 函数时。 这个警告会出现:

C:\Python26\lib\site-packages\Crypto\Util\randpool.py:40: RandomPool_Deprecation
Warning: This application uses RandomPool, which is BROKEN in older releases.  S
ee http://www.pycrypto.org/randpool-broken
  RandomPool_DeprecationWarning)

我知道这与 Paramiko 正在使用 PyCrypto 的一些已弃用功能有关。

我的问题是,有没有办法以编程方式抑制此警告? 我试过这个:

warnings.filterwarnings(action='ignore', \
category=DeprecationWarning, module='paramiko')

甚至这个:

warnings.filterwarnings(action='ignore', \
category=DeprecationWarning, module='randpool')

在 'import paramiko' 语句之前和 paramiko 特定的函数调用之前,但没有任何效果。 无论如何,此警告都会不断出现。 如果有帮助,这里是打印警告的第三方库中的代码:

在 randpool.py 中:

from Crypto.pct_warnings import RandomPool_DeprecationWarning
import Crypto.Random
import warnings

class RandomPool:
    """Deprecated.  Use Random.new() instead.

    See http://www.pycrypto.org/randpool-broken
    """
    def __init__(self, numbytes = 160, cipher=None, hash=None, file=None):
        warnings.warn("This application uses RandomPool, which is BROKEN in older releases.  See http://www.pycrypto.org/randpool-broken",
            RandomPool_DeprecationWarning)

如果您知道解决此问题的方法,请帮助我关闭此警告。

最简单的方法是警告模块在这里建议:

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    import paramiko

warnings.filterwarningsmodule参数采用区分大小写的正则表达式,该表达式应与完全限定的模块名称匹配,因此

warnings.filterwarnings(
    action='ignore',
    category=DeprecationWarning,
    module=r'.*randpool'
)

warnings.filterwarnings(
    action='ignore',
    category=DeprecationWarning,
    module=r'Crypto\.Utils\.randpool'
)

应该工作。 您可能需要编写RandomPool_DeprecationWarning明确,而不是DeprecationWarning如果由于某种原因RandomPool_DeprecationWarning不是一个子类DeprecationWarning

您还可以在调用脚本时通过将-W选项传递给解释器来禁用命令行上的警告,如下所示:

$ python -W ignore::RandomPool_DeprecationWarning:Crypto.Utils.randpool: my_script.py

-W采用格式为action:message:category:module:lineno过滤器,此时module必须与引发警告的(完全限定的)模块名称完全匹配。

请参阅https://docs.python.org/2/library/warnings.html?highlight=warnings#the-warnings-filterhttps://docs.python.org/2/using/cmdline.html#cmdoption-w

仅过滤特定警告:

with warnings.catch_warnings():
    warnings.simplefilter('ignore', SpecificWarningObject)

    #do something that raises a Warning

最灵活的方法是将warnings.filterwarnings()warnings.catch_warnings()上下文管理器结合起来。 通过这种方式,您filterwarnings的灵活性,但过滤仅适用于with块:

import warnings
from Crypto.pct_warnings import RandomPool_DeprecationWarning

with warnings.catch_warnings():
    warnings.filterwarnings(
        action='ignore',
        category=RandomPool_DeprecationWarning,
        message='This application uses RandomPool, which is BROKEN in older releases')
   
    # Do stuff that causes the warning

暂无
暂无

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

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