【发布时间】:2023-02-14 00:34:28
【问题描述】:
如果发出警告,如何跳过迭代
假设我有下面的代码
import warnings
# The function that might raise a warning
def my_func(x):
if x % 2 != 0:
warnings.warn("This is a warning")
return "Problem"
else:
return "No Problem"
for i in range(10):
try:
# code that may raise a warning
k = my_func(i)
except Warning:
# skip to the next iteration if a warning is raised
continue
# rest of the code
print(i, " : ",k) # Only print this if warning was not raised in try:except
我希望它只打印偶数,因为 my_funct(i) 会对奇数发出警告
【问题讨论】:
-
您需要使用warning filters 将警告转为异常。
标签: python