Search code examples
pythonnumpywarningsabort

How to abort a python script when a warning is raised


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!