How to disable Python warnings?

How to disable Python warnings?

Look at the Temporarily Suppressing 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 dont 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
<stdin>:3: UserWarning: you are warned!
after
>>> warnings.filterwarnings(ignore)
>>> f()
before
after

Theres the -W option.

python -W ignore foo.py

How to disable Python warnings?

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

How to disable Python warnings?

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 youre 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

Leave a Reply

Your email address will not be published. Required fields are marked *