918

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?

3
  • 17
    @MartinSamson I generally agree, but there are legitimate cases for ignoring warnings. I get several of these from using the valid Xpath syntax in defusedxml: FutureWarning: This search is broken in 1.3 and earlier, and will be fixed in a future version. If you rely on the current behaviour, change it to [this other thing]. I would rather ignore the warnings now and wait for it to be silently fixed than write needlessly ugly code just to avoid a harmless warning.
    – Pedro
    Commented Dec 22, 2016 at 16:56
  • 5
    disable specific warnings: stackoverflow.com/questions/9134795/… Commented Nov 30, 2018 at 8:48
  • 18
    "Python doesn't throw around warnings for no reason." But some developers do. I am using a module that throws a useless warning despite my completely valid usage of it.
    – zenzic
    Commented Mar 29, 2022 at 22:46

14 Answers 14

1160

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()

# Or if you are using > Python 3.11:
with warnings.catch_warnings(action="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
9
  • 16
    @Framester - yes, IMO this is the cleanest way to suppress specific warnings, warnings are there in general because something could be wrong, so suppressing all warnings via the command line might not be the best bet.
    – Mike
    Commented Jan 22, 2013 at 16:34
  • 1
    @Framester - I listed the other option with an example as well... I don't like it as much (for reason I gave in the previous comment) but at least now you have the tools.
    – Mike
    Commented Jan 22, 2013 at 16:54
  • 96
    If you only expect to catch warnings from a specific category, you can pass it using the category argument: warnings.filterwarnings("ignore", category=DeprecationWarning)
    – ostrokach
    Commented Jun 12, 2017 at 1:20
  • 1
    This is useful for me in this case because html5lib spits out lxml warnings even though it is not parsing xml. Thanks
    – james-see
    Commented Jul 25, 2017 at 17:38
  • 14
    There is also a useful parameter for the warnings.filterwarnings function: module. It allows you to ignore warnings from specified module.
    – username
    Commented Mar 19, 2018 at 10:53
698

There's the -W option.

python -W ignore foo.py
2
  • 7
    To ignore only specific message you can add details in parameter. man python describes it in details excepts module name specification. I spent much time guessing it. Finally i got this command python3 -W ignore::UserWarning:git.cmd:914 ./test.py for warning /usr/local/lib/python3.4/dist-packages/git/cmd.py:914: UserWarning: Python 3.5 support is deprecated... Commented Apr 29, 2021 at 7:09
  • If using ipython is there a way to do this when calling a function? Commented Jan 14, 2022 at 11:50
231

Not to make it complicated, just use these two lines on the top

import warnings
warnings.filterwarnings('ignore')
0
188

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
4
  • 2
    This is especially useful to ignore warnings when performing tests. Using tox, adding PYTHONWARNINGS=ignore to setenv makes output less dirty. Commented Nov 13, 2016 at 11:44
  • 2
    Very useful for AWS CLI as well.
    – mckenzm
    Commented Aug 9, 2019 at 23:37
  • 1
    But this doesn't ignore the deprecation warning. May I ask how to include that one?
    – Wey Shi
    Commented Nov 16, 2019 at 8:31
  • 1
    since I am loading environment variables for other purposes in my .env file I added the line PYTHONWARNINGS=ignore and it worked like a charm (works for python 3.10)
    – Ace
    Commented Mar 23, 2022 at 15:31
147

If you don't want something complicated, then:

import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
1
  • 34
    And to turn things back to the default behavior: warnings.filterwarnings("default", category=FutureWarning) Commented Apr 14, 2019 at 0:47
116

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.

0
96

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.

1
  • This is perfect since it will not disable all warnings in later execution Commented Apr 7, 2020 at 9:33
56

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")
18
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.

7

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.

6

For example you can ignore this warning:

InsecureRequestWarning: Unverified HTTPS request is being made to host...

import warnings

warnings.filterwarnings(
    action="ignore",
    message=".*Unverified HTTPS.*",
)
5

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...
1
  • 1
    The wording is confusing, but there's 2 kinds of "warnings" and the one mentioned by OP isn't put into logging unless you call logging.captureWarnings(True). They're specifically talking about the warnings module that outputs to STDERR and not logging messages with level WARNING. Commented Dec 9, 2021 at 14:18
1

I have written a decorator that makes it very easy to ignore warnings only in specific function definitions:

import functools
import warnings

from typing import Callable

def ignore_warnings(category: Warning):
    def ignore_warnings_decorator(func: Callable):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", category=category)
                return func(*args, **kwargs)
        return wrapper
    return ignore_warnings_decorator

Example usage:

@ignore_warnings(category=DeprecationWarning)
def foo() -> None:
    # imagine this function below would throw a deprecation
    # warning that we willfully want to ignore because we know better:
    bar()
-11

Warnings are output via stderr and the simple solution is to append to the command.

2> /dev/null

Alternatively, redirect errors to a file, so they are retained without dirtying the console output.

2> my-cli-errors.log

1
  • 12
    Thanks for taking the time to answer. Please keep answers strictly on-topic though: You mention quite a few things which are irrelevant to the question as it currently stands, such as CentOS, Python 2.6, cryptography, the urllib, back-porting. You can edit your question to remove those bits. If you want to know more details from the OP, leave a comment under the question instead.
    – FriendFX
    Commented Jan 23, 2017 at 3:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.