我必须每 5 秒重新加载 Streamlit 图表,以便在 XLSX 报告中可视化新数据。
如何实现这一目标?
import streamlit as st
import pandas as pd
import os
mainDir = os.path.dirname(__file__)
filePath = os.path.join(mainDir, "sources\\test.xlsx")
df = pd.read_excel(filePath)
option1 = 'Product'
option2 = 'Quantity'
df = df[[option1, option2]].set_index(option1)
st.write('Product Quantity')
st.area_chart(df)
Streamlit 会识别您的每一次源代码变化。因此,基于这个前提,实现此目的的一种方法是创建一个空的“dummy.py”文件,该文件将由主脚本导入,并由同时运行的另一个脚本每 5 秒更新一次:
-
在主脚本的同一文件夹中创建一个空的“dummy.py”文件;
-
在同一文件夹中创建一个名为“refresher.py”的脚本;
-
现在将以下 While 循环放入“refresher.py”文件中,以便每 5 秒使用随机数(已注释)更新“dummy.py”:
from random import randint
import time
import os
def refresher(seconds):
while True:
mainDir = os.path.dirname(__file__)
filePath = os.path.join(mainDir, 'dummy.py')
with open(filePath, 'w') as f:
f.write(f'# {randint(0, 10000)}')
time.sleep(seconds)
refresher(5)
-
使用您的 Streamlit 图表代码将以下行添加到脚本中: """ from dummy import * """
-
运行“refresher.py”脚本;
-
使用您的图表运行 Streamlit 脚本;
-
从现在开始,Streamlit 会将“dummy.py 文件”中的任何修改识别为源代码中的修改;
-
一旦网页完全加载,它会提醒您源文件已更改。单击“始终重新运行”即可。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)