Skip to content

Instantly share code, notes, and snippets.

@tvst
Last active January 13, 2022 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tvst/ef477845ac86962fa4c92ec6a72bb5bd to your computer and use it in GitHub Desktop.
Save tvst/ef477845ac86962fa4c92ec6a72bb5bd to your computer and use it in GitHub Desktop.
DO NOT USE! There's an experimental API in Streamlit now, called st.experimental_rerun()
from streamlit.ScriptRequestQueue import RerunData
from streamlit.ScriptRunner import RerunException
from streamlit.server.Server import Server
import streamlit.ReportThread as ReportThread
def rerun():
"""Rerun a Streamlit app from the top!"""
widget_states = _get_widget_states()
raise RerunException(RerunData(widget_states))
def _get_widget_states():
# Hack to get the session object from Streamlit.
ctx = ReportThread.get_report_ctx()
session = None
session_infos = Server.get_current()._session_infos.values()
for session_info in session_infos:
if session_info.session._main_dg == ctx.main_dg:
session = session_info.session
if session is None:
raise RuntimeError(
"Oh noes. Couldn't get your Streamlit Session object"
'Are you doing something fancy with threads?')
# Got the session object!
return session._widget_states
@treuille
Copy link

"Oh noes..." 🤣

@hcoohb
Copy link

hcoohb commented Dec 16, 2019

Thanks for sharing this!

It does trigger a rerun of the script,
However I found that all values are reset to their default values and are not reflecting the state of the UI.
example:
if the code has gui_pipeline_debug = st.sidebar.checkbox("Debug", value=False)
and when I check it, then gui_pipeline_debug is True,
But if a rerun is called later, on the next run, gui_pipeline_debug is now False although the checkbox is still ticked on the web page.

Am I doing something wrong, or is there a way to fix this?
Thanks

@demmerichs
Copy link

demmerichs commented Mar 24, 2020

I updated the gist to work with the more recent streamlit versions 0.54.0 and upwards. The fork can be found here!

@goraj
Copy link

goraj commented Apr 10, 2020

Script won't work for 0.57.3, fixed version: https://gist.github.com/goraj/47f4e365a13b11c4c0eba4f233acda76

@tfriedel
Copy link

tfriedel commented May 26, 2020

I get RecursionErrors after about a 1000 reruns. Must be because of the nested raised RerunExceptions.

I think it can be fixed using session.request_rerun()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment