我希望能够在使用matplotlib动画功能进行绘图时捕获错误。
这对我来说是必要的,因为我有一个程序可能会发生在几个循环之后updatefig函数中发生错误。我想继续在脚本中保存到目前为止生成的所有数据。
运行下面的代码只会导致以下输出,而不是抛出错误:
流程已完成退出代码1
我试图将 try except 子句放在我能想到的所有位置但是从来没有能够进入最后一次打印()。
请参阅此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')
答案 0 :(得分:1)
由于您尝试将int p1;
cout << "Person 1:", cin >> p1;
与string
连接起来,因此出现错误:
更正错误:
int
捕获错误,保存数据,然后继续:
import matplotlib
matplotlib.use('TkAgg')
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 will not fail
if counter > 10:
b = 0
print('bla ' + str(b))
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
print('do other stuff now, e.g. save x and y')