Python-从变化的文本文件更新实时图形 [英] Python - live graph update from a changing text file

查看:168
本文介绍了Python-从变化的文本文件更新实时图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程,每2秒将其连续写入一个文本文件中一次. Matplotlib图(实时更新图)引用了同一文件.

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?

这是我的主要功能

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无关,但与您如何将数据读取和写入文本文件有关.

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文件对象通常默认情况下是行缓冲的,因此,当您从FileWriter线程内部调用f.write(str(i)+','+str(j)+'\n')时,文本文件不会立即在磁盘上更新.因此,open("sampleText.txt","r").read()返回一个空字符串,因此您没有要绘制的数据.

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.

要强制立即"更新文本文件,可以在写入后立即调用f.flush(),也可以在打开文件时将缓冲区大小设置为零,例如. f = open('sampleText.txt', 'w', 0)(也请参见此先前的SO问题).

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

这篇关于Python-从变化的文本文件更新实时图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆