i have a thread that writes continuously into a text file for every 2 seconds.
the same file is referenced by a Matplotlib graph (live updating graph).
so when i start the script, i open up a graph and start the file writing process on a thread. the file is getting updated but not my graph. only after the file writing is complete the data on the file gets represented on the graph.
but this is not the concept of live graphs. i want the data representation to be shown as and when the data is being written into the file. what am i doing wrong here?
this is my Main function
def Main():
t1=Thread(target=FileWriter)
t1.start()
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
print("done")
My file writing function
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
my Graph function
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)
解决方案
The problem is unrelated to matplotlib, but rather it has to do with how you're reading and writing your data to the text file.
Python file objects are usually line-buffered by default, so when you call f.write(str(i)+','+str(j)+'\n') from inside your FileWriter thread, your text file is not immediately updated on disk. Because of this, open("sampleText.txt","r").read() is returning an empty string, and therefore you have no data to plot.
To force the text file to be updated "instantly", you could either call f.flush() immediately after writing to it, or you could set the buffer size to zero when you open the file, e.g. f = open('sampleText.txt', 'w', 0) (see this previous SO question as well).