PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 17, 2022

[FIXED] How to abort a python script when a warning is raised

 July 17, 2022     abort, numpy, python, warnings     No comments   

Issue

I used Spyder (Python 3.6)

My problem is with one of my loop "for", I get at one moment " RuntimeWarning: divide by zero encountered in true_divide "

The problem is (because it goes so fast with my "tqdm") I can't know where or when it's raised.

I tried to use :

print("ii = " + str(ii) + ", jj = " + str(jj) + ... + ", zz = " + str(zz))

Or :

try :
    blablabla 
except:
     sys.exit

But it's really slow for the first and the second doesn't work because it's not an error but just a warning. Is there any way to stop the script when the warning is raised so I can investigate by myself ?

Thanks in advance.


Solution

You need to change the way numpy is dealing with errors:

>>> arr1 = numpy.random.randint(0, 123, (10,))
>>> arr2 = numpy.random.randint(0,5, (10,))
>>> arr1, arr2
(array([  0,   7,  15,  89, 110,  82,  53,  73,  64,  55]), array([2, 1, 3, 0, 2, 0, 2, 0, 0, 0]))
>>> arr1/arr2
__main__:1: RuntimeWarning: divide by zero encountered in true_divide
array([  0. ,   7. ,   5. ,   inf,  55. ,   inf,  26.5,   inf,   inf,   inf])

Use seterr:

>>> numpy.seterr(divide='raise') # returns old settings
{'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}

Now, the error is raised, and you can use error-handling:

>>> arr1/arr2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FloatingPointError: divide by zero encountered in true_divide

So something like:

>>> try:
...     arr1/arr2
... except FloatingPointError as e:
...     print("can't divide by zero!")
...
can't divide by zero!


Answered By - juanpa.arrivillaga
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing