问题描述
如何在不重新启动python的情况下再次看到警告.现在我只看到一次.
How can I see a warning again without restarting python. Now I see them only once.
例如,考虑以下代码:
import pandas as pd
pd.Series([1]) / 0
我知道
RuntimeWarning: divide by zero encountered in true_divide
但是当我再次运行它时,它会静默执行.
But when I run it again it executes silently.
如何在不重新启动python的情况下再次看到警告?
我试图做
del __warningregistry__
但这无济于事.
似乎只在其中存储某些类型的警告.例如,如果我这样做:
Seems like only some types of warnings are stored there.For example if I do:
def f():
X = pd.DataFrame(dict(a=[1,2,3],b=[4,5,6]))
Y = X.iloc[:2]
Y['c'] = 8
然后这只会在第一次调用f()
时发出警告.但是,现在如果执行del __warningregistry__
时,我可以再次看到警告.
then this will raise warning only first time when f()
is called.However, now when if do del __warningregistry__
I can see the warning again.
第一次警告和第二次警告有什么区别?为什么只有第二个存储在此__warningregistry__
中?第一个存储在哪里?
What is the difference between first and second warning? Why only the second one is stored in this __warningregistry__
? Where is the first one stored?
推荐答案
只要您在脚本的开头执行以下操作,就无需重新启动.
As long as you do the following at the beginning of your script, you will not need to restart.
import pandas as pd
import numpy as np
import warnings
np.seterr(all='warn')
warnings.simplefilter("always")
此时,每次您尝试除零时,它将显示
At this point every time you attempt to divide by zero, it will display
RuntimeWarning: divide by zero encountered in true_divide
说明:
Explanation:
我们正在设置几个警告过滤器.第一个( np.seterr
)告诉NumPy如何它应该处理警告.我已将其设置为在 all 上显示警告,但是如果您只想查看除以零警告,请将参数从all
更改为divide
.
We are setting up a couple warning filters. The first (np.seterr
) is telling NumPy how it should handle warnings. I have set it to show warnings on all, but if you are only interested in seeing the Divide by zero warnings, change the parameter from all
to divide
.
接下来,我们更改希望warnings
模块始终显示警告的方式.为此,我们设置了警告过滤器.
Next we change how we want the warnings
module to always display warnings. We do this by setting up a warning filter.
在报告此问题的错误报告中对此进行了描述:
This is described in the bug report reporting this issue:
顺便说一句, bug 已针对版本3.4和3.5修复为关闭状态.
Incidentally, the bug has been closed as fixed for versions 3.4 and 3.5.
这篇关于如何完全重置警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!