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

2024-05-21 01:20:39 发布

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

我在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)

如果你知道解决这个问题的方法,请帮我关闭这个警告。


Tags: 代码orgimportnonehttp警告paramikowww
3条回答

最简单的方法是,正如警告模块建议的那样here

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

仅筛选特定警告:

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

    #do something that raises a Warning

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

相关问题 更多 >