python 写入文件 刷新_Python-从变化的文本文件更新实时图形

在Python中,一个线程每两秒写入文本文件,而Matplotlib图表实时更新该文件数据。但发现只有文件写入完成后,图表才显示数据。问题在于文件的缓冲导致数据未即时更新。解决方案是使用f.flush()强制刷新文件或者打开文件时设置缓冲大小为0。
摘要由CSDN通过智能技术生成

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值