Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Python warnings?

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?

like image 504
Framester Avatar asked Jan 22 '13 16:01

Framester


People also ask

How do I enable warnings in Python?

To enable warnings run python with the -Wdefault or -Wd switch.


2 Answers

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 
like image 133
Mike Avatar answered Sep 22 '22 22:09

Mike


There's the -W option.

python -W ignore foo.py 
like image 38
Pavel Anossov Avatar answered Sep 26 '22 22:09

Pavel Anossov