How to disable Python warnings?

PythonSuppress Warnings

Python Problem Overview


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 disable warnings for single functions. But I don't want to change so much of the code.

Is there a flag like python -no-warning foo.py?

What would you recommend?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

There's the -W option.

python -W ignore foo.py

Solution 3 - Python

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

Solution 4 - Python

If you don't want something complicated, then:

import warnings
warnings.filterwarnings("ignore", category=FutureWarning)

Solution 5 - Python

This is an old question but there is some newer guidance in PEP 565 that to turn off all warnings if you're writing a python application you should use:

import sys
import warnings

if not sys.warnoptions:
    warnings.simplefilter("ignore")

The reason this is recommended is that it turns off all warnings by default but crucially allows them to be switched back on via python -W on the command line or PYTHONWARNINGS.

Solution 6 - Python

Not to make it complicated, just use these two lines

import warnings
warnings.filterwarnings('ignore')

Solution 7 - Python

When all else fails use this: https://github.com/polvoazul/shutup

pip install shutup

then add to the top of your code:

import shutup; shutup.please()

Disclaimer: I am the owner of that repository. I wrote it after the 5th time I needed this and couldn't find anything simple that just worked.

Solution 8 - Python

If you know what are the useless warnings you usually encounter, you can filter them by message.

import warnings

#ignore by message
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")

#part of the message is also okay
warnings.filterwarnings("ignore", message="divide by zero encountered") 
warnings.filterwarnings("ignore", message="invalid value encountered")

Solution 9 - Python

import sys
if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")

Change ignore to default when working on the file or adding new functionality to re-enable warnings.

Solution 10 - Python

I realise this is only applicable to a niche of the situations, but within a numpy context I really like using np.errstate:

np.sqrt(-1)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
nan

However, using np.errstate:

with np.errstate(invalid='ignore'):
    np.sqrt(-1)
nan

The best part being you can apply this to very specific lines of code only.

Solution 11 - Python


More pythonic way to ignore WARNINGS


Since 'warning.filterwarnings()' is not suppressing all the warnings, i will suggest you to use the following method:

import logging
    
for name in logging.Logger.manager.loggerDict.keys():
    logging.getLogger(name).setLevel(logging.CRITICAL)

#rest of the code starts here...

OR,

If you want to suppress only a specific set of warnings, then you can filter like this:

import logging
    
for name in logging.Logger.manager.loggerDict.keys():
    if ('boto' in name) or ('urllib3' in name) or ('s3transfer' in name) or ('boto3' in name) or ('botocore' in name) or ('nose' in name):
            logging.getLogger(name).setLevel(logging.CRITICAL)

#rest of the code starts here...

Solution 12 - Python

warnings are output via stderr and the simple solution is to append '2> /dev/null' to the CLI. this makes a lot of sense to many users such as those with centos 6 that are stuck with python 2.6 dependencies (like yum) and various modules are being pushed to the edge of extinction in their coverage.

this is especially true for cryptography involving SNI et cetera. one can update 2.6 for HTTPS handling using the proc at: https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl-py2

the warning is still in place, but everything you want is back-ported. the re-direct of stderr will leave you with clean terminal/shell output although the stdout content itself does not change.

responding to FriendFX. sentence one (1) responds directly to the problem with an universal solution. sentence two (2) takes into account the cited anchor re 'disable warnings' which is python 2.6 specific and notes that RHEL/centos 6 users cannot directly do without 2.6. although no specific warnings were cited, para two (2) answers the 2.6 question I most frequently get re the short-comings in the cryptography module and how one can "modernize" (i.e., upgrade, backport, fix) python's HTTPS/TLS performance. para three (3) merely explains the outcome of using the re-direct and upgrading the module/dependencies.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFramesterView Question on Stackoverflow
Solution 1 - PythonMikeView Answer on Stackoverflow
Solution 2 - PythonPavel AnossovView Answer on Stackoverflow
Solution 3 - PythonHolger BilleView Answer on Stackoverflow
Solution 4 - PythonAbhishek JainView Answer on Stackoverflow
Solution 5 - PythonChris_RandsView Answer on Stackoverflow
Solution 6 - PythonPrajot KuvalekarView Answer on Stackoverflow
Solution 7 - PythonpolvoazulView Answer on Stackoverflow
Solution 8 - Pythonuser3226167View Answer on Stackoverflow
Solution 9 - PythonArthur BowersView Answer on Stackoverflow
Solution 10 - PythonjorijnsmitView Answer on Stackoverflow
Solution 11 - PythonSafvan CKView Answer on Stackoverflow
Solution 12 - PythonjvpView Answer on Stackoverflow