我有一个线程,每 2 秒连续写入一个文本文件。 同一个文件被 Matplotlib 图(实时更新图)引用。
所以当我启动脚本时,我打开一个图表并在一个线程上启动文件写入过程。该文件正在更新,但不是我的图表。只有在文件写入完成后,文件中的数据才会显示在图表上。
但这不是活图的概念。我希望在将数据写入文件时显示数据表示形式。我在这里做错了什么?
这是我的主要功能
def Main():
t1=Thread(target=FileWriter)
t1.start()
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
print("done")
我的文件写入功能
def FileWriter():
f=open('F:\\home\\WorkSpace\\FIrstPyProject\\TestModules\\sampleText.txt','w')
k=0
i=0
while (k < 20):
i+=1
j=randint(10,19)
data = f.write(str(i)+','+str(j)+'\n')
print("wrote data")
time.sleep(2)
k += 1
我的图形函数
def animate(i):
pullData = open("sampleText.txt","r").read()
dataArray = pullData.split('\n')
xar = []
yar = []
for eachLine in dataArray:
if len(eachLine)>1:
x,y = eachLine.split(',')
xar.append(int(x))
yar.append(int(y))
ax1.clear()
ax1.plot(xar,yar)
最佳答案
问题与 matplotlib 无关,而是与您如何读取数据以及将数据写入文本文件有关。
Python file objects are usually line-buffered by default ,所以当您从 FileWriter
线程中调用 f.write(str(i)+','+str(j)+'\n')
时,您的文本文件不会立即在磁盘上更新。因此,open("sampleText.txt","r").read()
返回一个空字符串,因此您没有要绘制的数据。
要强制“立即”更新文本文件,您可以在写入文件后立即调用 f.flush()
,也可以在打开文件时将缓冲区大小设置为零文件,例如f = open('sampleText.txt', 'w', 0)
(另见 previous SO question)。
关于Python - 从不断变化的文本文件更新实时图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33457040/