如何在numpy中获取RuntimeWarning的信息? [英] How to get the information of RuntimeWarning in numpy?
本文介绍了如何在numpy中获取RuntimeWarning的信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
try:
np.arccos(10)
except RuntimeWarning:
print('error')enter code here
但没有任何反应,我是新来的.
but nothing happens, I am a newer.
推荐答案
如果你想引起一个警告来引发一个异常,你可以使用 warnings.simplefilter("error")
这将强制警告变成异常,例如:
If you want to cause a warning to raise an exception than you can use warnings.simplefilter("error")
which will force the warning into an exception, e.g.:
In []:
import warnings
warnings.simplefilter("error")
try:
np.arccos(10)
except RuntimeWarning:
print('error')
Out[]:
error
或者,您可以使用 warnings.catch_warnings(record=True)
上下文管理器记录警告:
Alternative, you can record the warnings with warnings.catch_warnings(record=True)
context manager:
In []:
import warnings
with warnings.catch_warnings(record=True) as ws:
np.arccos(10)
for w in ws:
print(w.message)
Out[]:
invalid value encountered in arccos
这篇关于如何在numpy中获取RuntimeWarning的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文