0

.txt我正在尝试从更新的Notepad++ 文件中实时更新图表。换句话说,随机数被打印到文本文件中,然后 python 脚本从文本文件中读取数字并绘制它。

我假设需要多线程,以便这两个函数可以同时运行。我正在使用该schedule模块,因此我可以每 3 秒将随机数打印到文本文件中。这是我的代码:

import random
import schedule
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from threading import Thread

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)


def gen_text():
    num1 = random.randint(1, 100)
    num2 = random.randint(1, 100)
    print(str(num1) + ',' + str(num2), file=open('TEXT FILE', 'a'))

schedule.every(3).seconds.do(gen_text)
pull_data = open('TEXT FILE', 'r').read()


def animate(i):
    data_array = pull_data.split('\n')
    xar = []
    yar = []
    for each_line in data_array:
        if len(each_line) > 1:
            x, y = each_line.split(',')
            xar.append(int(x))
            yar.append(int(y))
    ax.clear()
    ax.plot(xar, yar)

if __name__ == '__main__':
    Thread(target=animate).start()
    Thread(target=gen_text).start()
    ani = animation.FuncAnimation(fig, animate, interval=3000)
    plt.show()


while True:
    schedule.run_pending()
    for line in pull_data:
        Type = line.split(",")
        x = Type[0]
        y = Type[1]
        print(x, y)

这段代码只显示了一个 Matplotlib 图表,其中包含从以前的代码运行中绘制的线条。不是实时更新的。多线程是正确的方法吗?如果没有,那么我该如何解决这个问题?

4

0 回答 0