如果不重新启动python,我怎么能再次看到警告呢。现在我只见过他们一次。在
以以下代码为例:
import pandas as pd
pd.Series([1]) / 0
我明白了
^{pr2}$但当我再次运行它时,它会无声地执行。在
如果不重新启动python,我如何才能再次看到警告?
我已经试过了
del __warningregistry__
但这没用。在
似乎只有一些类型的警告存储在那里。 例如,如果我这样做:
def f():
X = pd.DataFrame(dict(a=[1,2,3],b=[4,5,6]))
Y = X.iloc[:2]
Y['c'] = 8
那么这只会在第一次调用f()
时发出警告。
但是,现在当if do del __warningregistry__
时,我可以再次看到警告。在
第一次和第二次警告有什么区别?为什么只有第二个存储在这个__warningregistry__
中?第一个放在哪里?在
只要在脚本开始时执行以下操作,就不需要重新启动。在
在这一点上,每次你试图除以零,它将显示
^{pr2}$说明:
我们正在设置一些警告过滤器。第一个(^{} )告诉NumPy它应该如何处理警告。我已经将其设置为在all上显示警告,但是如果您只想看到被零除的警告,请将参数从
all
更改为divide
。在接下来,我们更改希望
warnings
模块始终显示警告的方式。我们通过设置warning filter来实现这一点。在报告此问题的bug report中对此进行了描述:
顺便说一句,bug在3.4和3.5版本中已经被关闭。在
warnings
是一个非常棒的标准库模块。你会喜欢了解它的:)有点背景
warnings
的默认行为是只在第一次出现时显示来自特定行的特定警告。例如,以下代码将导致向用户显示两个警告:你有几个选择来改变这种行为。在
选项1:重置警告注册表
当您希望python“忘记”以前看到的警告时,可以使用^{} :
^{pr2}$请注意,这也会重置您所做的任何警告配置更改。这让我想到。。。在
选项2:更改警告配置
warnings module documentation更详细地介绍了这一点,但是有一个简单的选择就是使用
simplefilter
来更改默认行为。在由于这是一个全局配置更改,它具有全局影响,您可能希望避免这些影响(应用程序中任何位置的所有警告都将每次显示)。一个不那么激烈的选择是使用上下文管理器:
对于特定类型的警告,还可以使用更精细的选项来更改配置。为此,请查看docs。在
相关问题 更多 >
编程相关推荐