Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Streamlit reloads every 5 seconds?

I have to reload a Streamlit chart every 5 seconds, in order to visualize the new data in a XLSX report. How to achieve this?

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)
like image 237
Julio S. Avatar asked Sep 02 '25 09:09

Julio S.


1 Answers

Streamlit recognizes every time your source code changes. So, based on this premise, one way to achieving this is to create an empty "dummy.py" file, which will be imported by the main script and updated every 5 seconds by another script running simultaneously:

  • create an empty "dummy.py" file inside the same folder of your main script;

  • create a script called "refresher.py" in the same folder;

    • now put the following While loop inside your "refresher.py" file, in order to update the "dummy.py" with a random number (commented) every 5 seconds:

      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)
      
  • add the following line to the script with your Streamlit chart code: """   from dummy import *   """

  • run the "refresher.py" script;

  • run the Streamlit script with your chart;

  • Streamlit from now on will recognize any modifications in the "dummy.py file" as a modification in the source code;

  • Once the web page is fully loaded, it will alert you the source file was changed. Click on " Alway rerun" and that's it.

like image 113
Julio S. Avatar answered Sep 04 '25 22:09

Julio S.