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

前端 未结 4 2040
忘了有多久
忘了有多久 2021-02-05 00:55

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:

C         


        
相关标签:
4条回答
  • 2021-02-05 01:03

    To filter only a specific warning:

    with warnings.catch_warnings():
        warnings.simplefilter('ignore', SpecificWarningObject)
    
        #do something that raises a Warning
    
    0 讨论(0)
  • 2021-02-05 01:15

    The module argument to warnings.filterwarnings takes a case-sensitive regular expression which should match the fully qualified module name, so

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

    or

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

    should work. You may need to write RandomPool_DeprecationWarning explicitly instead of DeprecationWarning if for some reason RandomPool_DeprecationWarning is not a subclass of DeprecationWarning.

    You can also disable the warning on the command line when you invoke the script by passing the -W option to the interpreter like so:

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

    The -W takes filters in the format action:message:category:module:lineno, where this time module must exactly match the (fully-qualified) module name where the warning is raised.

    See https://docs.python.org/2/library/warnings.html?highlight=warnings#the-warnings-filter and https://docs.python.org/2/using/cmdline.html#cmdoption-w

    0 讨论(0)
  • 2021-02-05 01:15

    The most flexible way is to combine warnings.filterwarnings() with the warnings.catch_warnings() context manager. This way you ge the flexibility of filterwarnings but the filtering is only applied inside the with block:

    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
    
    
    0 讨论(0)
  • 2021-02-05 01:23

    Easiest way would be as the warnings module suggests here:

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        import paramiko
    
    0 讨论(0)
提交回复
热议问题