How to monitor the filesystem and have streamlit updated when some files are modified?

Hello @tim ,
thanks for the detailed explanation.
Your solution has worked in my problem!

Here, I propose another solution without any dummy files.

Environment

  • python = 3.7.10
  • streamlit = 0.80.0

Objective

To rerun the following application automatically when watched.csv is updated.

[main.py]

from datetime import datetime as dt
import pandas as pd
import streamlit as st

st.text(dt.now())
st.dataframe(pd.read_csv('watched.csv'))

Idea

Streamlit already uses watchdog to monitor source codes.
Add watched.csv to the list of watched files in streamlit.

Solution

To add some lines to main.py to monitor watched.csv and rerun the application.

[main.py]

from datetime import datetime as dt
import pandas as pd
import streamlit as st

import os
from streamlit.server.server import Server
from streamlit.report_thread import get_report_ctx

# get report context
ctx = get_report_ctx()  
# get session id
session_id  = ctx.session_id  

# get session
server = Server.get_current()
session_info = server._session_info_by_id.get(session_id)
session = session_info.session

# register watcher
session._local_sources_watcher._register_watcher(
    os.path.join(os.path.dirname(__file__), 'watched.csv'), 
    'dummy:watched.csv'
)  
# Pep 8 does not recommended this because a single-leading-underscore indicates (weak) "internal."
# See https://pep8.org/#descriptive-naming-styles

st.text(dt.now())
st.dataframe(pd.read_csv('watched.csv'))

Note

Directory structure is follows:

./
    main.py
    watched.csv

I hope that this solution works well.
Thank you :smiley:

3 Likes