How to disable python warnings?

前端 未结 8 1032
醉梦人生
醉梦人生 2020-11-22 04:24

I am working with code that throws a lot of (for me at the moment) useless warnings using the warnings library. Reading (/scanning) the documentation I only found a way to d

8条回答
  •  死守一世寂寞
    2020-11-22 04:32

    Did you look at the suppress warnings section of the python docs?

    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:

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

提交回复
热议问题