我在python脚本中隐藏了一些简单的数学,并得到以下警告:
"警告:划分为零除以".
为了提供一些背景,我拿着两个值,并试图找到价值的百分比差值(a - b) / a,如果它超过一定的范围内,那么对其进行处理,但有时值a或b为零.
我想摆脱这个特定的警告(在一个特定的行),但到目前为止我找到的所有信息似乎告诉我如何停止所有警告(我不想要).
当我以前编写shell脚本时,我可以做这样的事情
code...
more code 2 > error.txt
even more code
Run Code Online (Sandbox Code Playgroud)
在那个例子中,我会得到'代码'和'甚至更多代码'命令的警告,但不是第二行.
这可能吗?
Ned*_*der 76
如果Scipy正在使用该warnings模块,那么您可以禁止特定警告.在程序开头试试这个:
import warnings
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")
Run Code Online (Sandbox Code Playgroud)
如果您希望这仅适用于代码的一部分,请使用警告上下文管理器:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")
# .. your divide-by-zero code ..
Run Code Online (Sandbox Code Playgroud)
Ble*_*der 12
我首先要避免被零除:
if a == 0:
# Break out early
# Otherwise the ratio makes sense
Run Code Online (Sandbox Code Playgroud)
如果你想在一行上压缩那个特定的numpy警告,numpy提供了一种方法:
with numpy.errstate(divide='ignore'):
# The problematic line
Run Code Online (Sandbox Code Playgroud)
Blenders 的答案非常适合这个问题。也许有人对另一种使用正则表达式或行号捕获特定警告的通用方法感兴趣:
抑制由特定行(此处为第 113 行)引起的警告:
import warnings
warnings.simplefilter('ignore',lineno=113)
Run Code Online (Sandbox Code Playgroud)
这种方法有一个缺点,即每次更改代码中的某些内容时,都需要重新调整 lineno。另一种选择是使用正则表达式捕获警告。以下代码将返回
import warnings
warnings.filterwarnings('ignore', message='.*show', )
warnings.warn('Do not do this!')
warnings.warn('Do not show this message')
>>> UserWarning: Do not do this!
warnings.warn('Do not do this!')
Run Code Online (Sandbox Code Playgroud)
* 符号之前的点是必需的,否则会返回错误
error: nothing to repeat
Run Code Online (Sandbox Code Playgroud)
这是在这个线程中讨论的
| 归档时间: |
|
| 查看次数: |
14427 次 |
| 最近记录: |