提问者:小点点

如何使Streamlit每5秒重新加载一次?


我必须每5秒重新加载一个流线图,以便在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)

共1个答案

匿名用户

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文件”中的任何修改识别为源代码中的修改;

    一旦网页被完全加载,它将警告您源文件已被更改。 点击“总是重新运行”,就这样。