Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of specific warning messages in python while keeping all other warnings as normal?

Tags:

python

I am doing some simple math recessively in a python script and am getting the follow warning:

"Warning: divide by zero encountered in divide".

To provide some context, I am taking two values and trying to find the percent difference in value (a - b) / a and if its above a certain range then process it, but sometimes the value of a or b is zero.

I want to get rid of this specific warning (at a specific line) but all the information I have found so far seems to show me how to stop all warnings (which I do not want).

When I used to write shell scripts, I could do something like this

code... more code 2 > error.txt even more code   

In that example, I would get the warnings for the 'code' and 'even more code' command but not for the second line.

Is this possible?

like image 842
Lostsoul Avatar asked Feb 03 '12 20:02

Lostsoul


People also ask

How do I ignore a specific warning in Python?

Use the filterwarnings() Function to Suppress Warnings in Python. The warnings module handles warnings in Python. We can show warnings raised by the user with the warn() function. We can use the filterwarnings() function to perform actions on specific warnings.

How do I ignore warnings in Jupyter?

To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings. Show activity on this post. from IPython. display import HTML HTML('''<script> var code_show_err = false; var code_toggle_err = function() { var stderrNodes = document.

How do I stop deprecation warning in Python?

When nothing else works: $ pip install shutup . Then at the top of the code import shutup;shutup. please() . This will disable all warnings.

Which method is used to display a warning message in Python?

showwarning() This method is used to display the warning to the user.


1 Answers

If Scipy is using the warnings module, then you can suppress specific warnings. Try this at the beginning of your program:

import warnings warnings.filterwarnings("ignore", message="divide by zero encountered in divide") 

If you want this to apply to only one section of code, then use the warnings context manager:

import warnings with warnings.catch_warnings():     warnings.filterwarnings("ignore", message="divide by zero encountered in divide")     # .. your divide-by-zero code .. 
like image 184
Ned Batchelder Avatar answered Sep 19 '22 05:09

Ned Batchelder