python - 从生成数据的函数中绘制实时数据
问题描述
我是编程的初学者,这是我第一次来这里。我正在尝试为 FEA analisys 编写一个脚本,该脚本从一个巨大的 .msg 文件中读取数据,该文件在模拟期间由第三个软件更新,然后绘制一个图表,每次 .msg 文件由第三个软件更新时都会自行更新。
使用我熟悉的工具,我的策略是:
构建一个函数,在分析完成之前主动读取数据(使用 while 循环),并从文本数据中获取感兴趣的值,并将其复制到另一个文件(data.txt),该文件将接收过滤后的数据。
构建另一个函数,读取过滤后的数据 (data.txt) 以生成绘图。
使用线程同步运行这两个函数
用他写的代码我得到了错误: 错误
数据收集似乎工作得很好,看起来问题是当我调用激活绘图函数的线程时,因为它需要一个我真的不知道如何定义的位置参数(i)。
我的代码:
import os
from itertools import count
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import time
import threading
time1 = os.path.getmtime('SM_1Gz_PT_1.msg')
def getdata():
index = count()
final=0
time1=''
residual_force_list=[] #lista com as linhas que contem a frase da largest residual force
residual_forces=[] #lista com o valor das residual forces
iteration=[]
while final == 0:
if (time1 != os.path.getmtime('SM_1Gz_PT_1.msg')): #acessa o horário da ultima alteraçao no msg
with open('SM_1Gz_PT_1.msg', 'rt') as lines:
for line in lines: #Checa se a análise foi ou nao completada e adiciona ultima
#linha de largest residual force à lista residual_force_list
if line[0:42].strip()=="THE ANALYSIS HAS BEEN COMPLETED":
final=1
# print(final)
if line[0:23].strip() == "LARGEST RESIDUAL FORCE": #add linha com ultima residual force a lista
residual_force_list.append(line)
residual_forces.append(float(residual_force_list[-1][36:47]))
force = residual_forces[-1]
data=open('data.txt','a')
data.write(f'{force},')
data.write(f'{next(index)+1} \n')
data.close()
print(residual_forces)
print(iteration, residual_forces)
print(final)
time1 = os.path.getmtime('SM_1Gz_PT_1.msg') #atualiza o horário da ultima modificação no msg
time.sleep(1) #reduz a frequência na qual o loop checa por atualizaçoes no msg
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
graph_data = open('data.txt','r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
y, x = line.split(',')
xs.append(int(x))
ys.append(float(y))
ax1.clear()
ax1.plot(xs, ys)
t1 = threading.Thread(target=getdata)
t2 = threading.Thread(target=animate)
t1.start()
t2.start()
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
解决方案
推荐阅读
- google-sheets - 我如何过滤只有时间的谷歌表格查询?
- azure - DNN Site azure DevOps 构建管道错误
- excel - 调用另一个子时 ByRef 类型不匹配
- django - 为 DeleteView 类编写的额外函数不起作用
- c++ - D3D12 SDKLayers dll 与 D3D12 Core dll 的 D3D12SDKVersion 不匹配
- html - 如何在 Pycharm 中将图像添加到 HTML?
- c# - ASP.NET Core 中 GraphQL 中的订阅。如何切换到 SubscriptionDocumentExecuter
- selenium - ElementClickInterceptedException:消息:元素点击被拦截:其他元素将接收点击 - 机器人中的点击元素或按钮失败
- javascript - 不和谐.js | 聊天机器人响应命令名称
- java - 如何在片段中禁用/(隐藏)自动生成的后退箭头?