Reputation: 35461
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?
Upvotes: 943
Views: 2210812
Reputation: 6618
Not to make it complicated, just use these two lines on the top
import warnings
warnings.filterwarnings('ignore')
Upvotes: 252
Reputation: 49403
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
Upvotes: 1187
Reputation: 171
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()
Upvotes: 1
Reputation: 59
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
Upvotes: -11
Reputation: 3411
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.*",
)
Upvotes: 6
Reputation: 651
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.
Upvotes: 19
Reputation: 3439
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")
Upvotes: 56
Reputation: 2528
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.
Upvotes: 121
Reputation: 1340
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...
Upvotes: 5
Reputation: 5741
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.
Upvotes: 7
Reputation: 2551
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 DeprecationWarning
s, but not the ones caused by:
import md5, sha
Upvotes: 191
Reputation: 4199
If you don't want something complicated, then:
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
Upvotes: 149
Reputation: 41168
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
.
Upvotes: 96