857

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?

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Framester
  • 33,341
  • 51
  • 130
  • 192
  • 15
    @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 Dec 22 '16 at 16:56
  • 5
    disable specific warnings: https://stackoverflow.com/questions/9134795/how-to-get-rid-of-specific-warning-messages-in-python-while-keeping-all-other-wa – user3226167 Nov 30 '18 at 08:48
  • You should fix your code. Python doesn't throw around warnings for no reason. – stidmatt Mar 18 '22 at 19:00
  • 9
    "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 Mar 29 '22 at 22:46

14 Answers14

1089

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
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Mike
  • 47,263
  • 29
  • 113
  • 177
  • So you have to wrap the code in each file with a `with warnings.catch_warnings():`? – Framester Jan 22 '13 at 16:31
  • 15
    @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 Jan 22 '13 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 Jan 22 '13 at 16:54
  • 86
    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 Jun 12 '17 at 01: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 Jul 25 '17 at 17:38
  • 12
    There is also a useful parameter for the `warnings.filterwarnings` function: `module`. It allows you to ignore warnings from specified module. – username Mar 19 '18 at 10:53
  • Re-iterating what worked along with the advice above: As mentioned in another post/comment, this solution should be implemented/added much before importing the library/function causing the warning. Nice approach would be to include it at the beginning of the program where we have import statements. – VinjaNinja Feb 01 '22 at 11:38
  • Your example of the right way to do things is not useful without further explanation. For example, do you insert your code in fxn() before or after warning.warn? Does this work in a multiprocessing example? Who knows? The python docs don't seem to help here and I didn't get this working in my code. The comment by -ostrokach works and requires no further explanation. – TheKillbot Jan 25 '23 at 17:03
660

There's the -W option.

python -W ignore foo.py
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
  • 4
    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...` – user3132194 Apr 29 '21 at 07:09
  • If using ipython is there a way to do this when calling a function? – Steven Thomas Jan 14 '22 at 11:50
182

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
phoenix
  • 7,988
  • 6
  • 39
  • 45
Holger Bille
  • 2,421
  • 1
  • 16
  • 20
  • 2
    This is especially useful to ignore warnings when performing tests. Using `tox`, adding `PYTHONWARNINGS=ignore` to `setenv` makes output less dirty. – Kurt Bourbaki Nov 13 '16 at 11:44
  • 2
    Very useful for AWS CLI as well. – mckenzm Aug 09 '19 at 23:37
  • 1
    But this doesn't ignore the deprecation warning. May I ask how to include that one? – Wey Shi Nov 16 '19 at 08: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 Mar 23 '22 at 15:31
170

Not to make it complicated, just use these two lines

import warnings
warnings.filterwarnings('ignore')
Prajot Kuvalekar
  • 5,128
  • 3
  • 21
  • 32
139

If you don't want something complicated, then:

import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
Gabriel L.
  • 4,678
  • 5
  • 25
  • 34
Abhishek Jain
  • 3,815
  • 2
  • 26
  • 26
101

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.

polvoazul
  • 2,208
  • 2
  • 19
  • 25
94

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.

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
51

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")
Prajot Kuvalekar
  • 5,128
  • 3
  • 21
  • 32
user3226167
  • 3,131
  • 2
  • 30
  • 34
17
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.

Prajot Kuvalekar
  • 5,128
  • 3
  • 21
  • 32
Arthur Bowers
  • 581
  • 5
  • 9
6

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.

gosuto
  • 5,422
  • 6
  • 36
  • 57
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...
Safvan CK
  • 1,140
  • 9
  • 18
  • 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`. – Tim Tisdall Dec 09 '21 at 14:18
3

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.*",
)
ahmnouira
  • 1,607
  • 13
  • 8
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()
Stefan
  • 115
  • 2
  • 7
-12

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

ocodo
  • 29,401
  • 18
  • 105
  • 117
jvp
  • 49
  • 2
  • 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 Jan 23 '17 at 03:50