簡體   English   中英

如何阻止np.vectorize打印我遇到的錯誤

[英]How to stop np.vectorize from printing error that I have caught

我最近從Python 2遷移到了Python 3,遇到了一個我不認為在Python 2中發生的問題(但我不完全確定。)

以下代碼打印出警告(但不會停止運行):

import numpy as np

@np.vectorize
def reciprocal(num):
    try:
        return 1/num
    except ZeroDivisionError:
        return 0

reciprocal(0)

#prints: RuntimeWarning: divide by zero encountered in long_scalars

即使我正在處理我的函數中的錯誤。

如何在打印/發生時停止此警告?

雖然在另一個解決方案中提供的suppressWarning裝飾器可以工作,但它可能有點過於允許,因為它根本不報告警告。 我認為,至少有時候,最好通過將警告提升為錯誤並將其處理為錯誤來明確警告。 使用warnings模塊可以輕松完成:

import numpy as np
import warnings

warnings.filterwarnings('error')

@np.vectorize
def reciprocal(num):
    try:
        return 1/num
    except ZeroDivisionError:
        # Now we end up here.
        return 0

reciprocal(0)

我創建了一個裝飾器來抑制函數的警告。 它使用與Python文檔中的臨時抑制警告相同的策略。

import warnings

def suppressWarnings(func):
    def wrapper(*args, **kwargs):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            func(*args, **kwargs)

    return wrapper

然后,你可以這樣做:

import numpy as np

@suppressWarnings
@np.vectorize
def reciprocal(num):
    try:
        return 1/num
    except ZeroDivisionError:
        return 0

reciprocal(0)

並且它不會打印出任何警告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM