How to disable python warnings?

前端 未结 8 1016
醉梦人生
醉梦人生 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:41

    You can also define an environment variable (new feature in 2010 - i.e. python 2.7)

    export PYTHONWARNINGS="ignore"
    

    Test like this: Default

    $ export PYTHONWARNINGS="default"
    $ python
    >>> import warnings
    >>> warnings.warn('my warning')
    __main__:1: UserWarning: my warning
    >>>
    

    Ignore warnings

    $ export PYTHONWARNINGS="ignore"
    $ python
    >>> import warnings
    >>> warnings.warn('my warning')
    >>> 
    

    For deprecation warnings have a look at how-to-ignore-deprecation-warnings-in-python

    Copied here...

    From documentation of the warnings module:

     #!/usr/bin/env python -W ignore::DeprecationWarning
    

    If you're on Windows: pass -W ignore::DeprecationWarning as an argument to Python. Better though to resolve the issue, by casting to int.

    (Note that in Python 3.2, deprecation warnings are ignored by default.)

    Or:

    import warnings
    
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=DeprecationWarning)
        import md5, sha
    
    yourcode()
    

    Now you still get all the other DeprecationWarnings, but not the ones caused by:

    import md5, sha
    

提交回复
热议问题