1
我在進程中運行動畫分散。一切工作正常,除了當我想退出一切時拋出一個異常。在python(matplotlib)中優雅地停止(不暫停)動畫劇情
import multiprocessing as mp
import time
from collections import deque
def start_colored_scores(nb_channels):
q = mp.Queue()
process = mp.Process(target=colored_scores,args=(q,nb_channels,4000))
process.start()
return process,q
def colored_scores(q,nb_channels,size):
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, axes = plt.subplots(nrows=nb_channels,ncols=1,sharex=True,sharey=True)
plt.axis([-1.0,1.0,-1.0,1.0])
scats = [axe.scatter([0], [0], c="white", s=size) for axe in axes]
def animate(i):
scores = q.get()
if scores is None : # this is the external signal saying things should stop
plt.close()
return [axe.scatter([0], [0], c="white", s=size) for axe in axes]
scats = []
for score,axe in zip(scores,axes):
score = max(min(1,1-score),0)
scats.append(axe.scatter([0], [0], c=(1-score,0,score), s=size))
return scats
ani = animation.FuncAnimation(fig, animate, interval=1, blit=True)
plt.show()
例如,這是工作的罰款:
_,q = start_colored_scores(2)
x = 0
right = 1
time_start = time.time()
while time.time()-time_start < 5:
if right==1 and x>1.0:
x = 1.0
right = -1
if right==-1 and x<0.0:
x = 0.0
right = 1
x+=right*0.02
q.put([x,1-x])
time.sleep(0.02)
q.put(None) # indicating I do not need plotting anymore
print "this is printed ... exception in the process ?"
的行爲如我所料:顯示和動畫5秒散開,然後程序繼續執行。唯一的問題是,拋出一個異常(我想在這個過程中)說:
AttributeError: 'NoneType' object has no attribute 'tk'
有沒有辦法做同樣的事情,但避免了異常?或者在某個地方發現這個異常?
您可以添加完整的堆棧跟蹤嗎? – Nathaniel