How to disable Python warnings?
Asked Answered
T

14

901

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?

Theriot answered 22/1, 2013 at 16:26 Comment(3)
@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.Alphonsa
disable specific warnings: #9135295Handicapper
"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.Disrepute
D
689

There's the -W option.

python -W ignore foo.py
Denumerable answered 22/1, 2013 at 16:28 Comment(2)
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...Asymptotic
If using ipython is there a way to do this when calling a function?Dogy
B
1147

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
Barksdale answered 22/1, 2013 at 16:31 Comment(9)
So you have to wrap the code in each file with a with warnings.catch_warnings():?Theriot
@Theriot - 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.Barksdale
@Theriot - 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.Barksdale
If you only expect to catch warnings from a specific category, you can pass it using the category argument: warnings.filterwarnings("ignore", category=DeprecationWarning)Moonmoonbeam
This is useful for me in this case because html5lib spits out lxml warnings even though it is not parsing xml. ThanksNovelty
There is also a useful parameter for the warnings.filterwarnings function: module. It allows you to ignore warnings from specified module.Volta
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.Rojo
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.Madriene
For Python 3.11 and above, simply with warnings.catch_warnings(action="ignore", category=WarningToBeIgnored):Kaffir
D
689

There's the -W option.

python -W ignore foo.py
Denumerable answered 22/1, 2013 at 16:28 Comment(2)
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...Asymptotic
If using ipython is there a way to do this when calling a function?Dogy
D
213

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

import warnings
warnings.filterwarnings('ignore')
Dialecticism answered 16/6, 2021 at 20:36 Comment(0)
P
185

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
Prohibit answered 15/7, 2013 at 12:59 Comment(4)
This is especially useful to ignore warnings when performing tests. Using tox, adding PYTHONWARNINGS=ignore to setenv makes output less dirty.Foehn
Very useful for AWS CLI as well.Sakhuja
But this doesn't ignore the deprecation warning. May I ask how to include that one?Ait
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)Irradiance
D
145

If you don't want something complicated, then:

import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
Dissoluble answered 13/12, 2018 at 14:7 Comment(1)
And to turn things back to the default behavior: warnings.filterwarnings("default", category=FutureWarning)Workhouse
S
115

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.

Scent answered 29/6, 2021 at 20:13 Comment(0)
V
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.

Volcano answered 6/2, 2018 at 18:48 Comment(1)
This is perfect since it will not disable all warnings in later executionSustentacular
H
53

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")
Handicapper answered 15/5, 2019 at 6:25 Comment(0)
P
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.

Perretta answered 26/2, 2021 at 10:18 Comment(0)
M
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.

Materi answered 25/5, 2020 at 21:32 Comment(0)
M
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...
Mikimikihisa answered 13/1, 2021 at 15:54 Comment(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.Avictor
E
5

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.*",
)
End answered 13/5, 2023 at 2:43 Comment(0)
A
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()
Aristotle answered 16/8, 2023 at 18:40 Comment(0)
B
-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

Basanite answered 23/1, 2017 at 2:43 Comment(1)
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.Ruy

© 2022 - 2024 — McMap. All rights reserved.