问题描述
我有这两个进程,其中有一个由 manager.list() 创建的列表在它们之间共享,一个称为 DATA() 并且它正在“生成”数据并附加到列表中,另一个是使用 Matplotlib 绘制该数据动画 FuncAnimation。
我遇到的问题是,一旦我将列表传递给 animate 函数
[ani = FuncAnimation(plt.gcf(),animate,fargs= (List,),interval=1000)]
该函数正在接收
有人知道为什么会这样吗?
import pandas as pd
import matplotlib.pyplot as plt
import multiprocessing as mp
from multiprocessing import freeze_support,Manager
import time
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')
my_c = ['x','y']
initial = [[1,3],[2,4],[3,8],[4,6],[5,[6,5],2],[7,7]]
df = pd.DataFrame(columns=my_c)
def data(List):
for i in initial:
#every 1 sec the list created with the manager.list() is updated
List.append(i)
#print(f"list in loop {List}")#making sure list is not empty
time.sleep(1)
def animate(List,i):
print(f"list in animate {type(List)}")# prints <class 'int'> instead of <class 'multiprocessing.managers.ListProxy'>
global df
for l in List:
print(f" for loop: {type(l)}")
df = df.append({'x':l[0],'y':l[1]},ignore_index = True)
plt.plot(df['x'],df['y'],label = "Price")
plt.tight_layout()
def run(List):
print(f"run funciton {type(List)}") # prints <class 'multiprocessing.managers.ListProxy'>
ani = FuncAnimation(plt.gcf(),interval=1000) #passes List as an argument to Animate function
plt.show()
if __name__ == '__main__':
manager = mp.Manager()
List = manager.list()
freeze_support()
p1 = mp.Process(target = run,args =(List,))
p2 = mp.Process(target = data,args=(List,))
p2.start()
p1.start()
p2.join()
p1.join()
解决方法
事实证明 animate 函数接收了 2 个参数。这个回应有更好的解释TypeError: method() takes 1 positional argument but 2 were given。我不得不将我的函数从 def animate(List) 修改为 animate(self,List)