我希望能够在使用matplotlib动画函数绘图时捕捉错误。在
这对我来说是必要的,因为我有一个程序,在这个程序中,updatefig函数在几个循环之后可能发生错误。然后我想在脚本中继续保存到那时为止生成的所有数据。在
运行以下代码而不是抛出错误,只会导致以下输出:
进程结束,退出代码1
我试图将try except子句放在我能想到的所有位置,但始终无法转到最后一个print()。在
请看这个MWE(摘自here):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
counter = 0
im = plt.imshow(f(x, y), animated=True)
def updatefig(*args):
global x, y, counter
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
counter += 1
# do something that might fail at one point (and will fail in this example)
if counter > 10:
b = 0
print('bla ' + b) # error
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
print('do other stuff now, e.g. save x and y')
出现错误,因为您正试图将
string
与int
连接:选项1:
更正错误:
选项2:
捕获错误,保存数据,然后继续:
^{pr2}$相关问题 更多 >
编程相关推荐