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

时间:2023-01-19 11:09:15

I am using Paramiko in my python code (for sftp). Everything works fine except that everytime I import or call a paramiko function. This warning would show up:

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

I know that this has to do with the fact that Paramiko is using some Deprecated functionalities of PyCrypto.

我知道这与Paramiko正在使用PyCrypto的一些不推荐的功能这一事实有关。

My question is, is there a way to suppress this warning programmatically ? I have tried this:

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

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

and even this:

甚至这个:

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

before 'import paramiko' statement and before paramiko-specific function calls, but nothing works. This warning keeps showing up no matter what. If it helps, here's the code in the third party library that prints the warning:

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

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

If you know a way around this, please help me shut this warning off.

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

2 个解决方案

#1


32  

Easiest way would be as the warnings module suggests here:

最简单的方法就像警告模块在这里建议的那样:

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

#2


2  

To filter only a specific warning:

仅过滤特定警告:

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

    #do something that raises a Warning

#1


32  

Easiest way would be as the warnings module suggests here:

最简单的方法就像警告模块在这里建议的那样:

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

#2


2  

To filter only a specific warning:

仅过滤特定警告:

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

    #do something that raises a Warning