Skip to content

Instantly share code, notes, and snippets.

@tvst
Created October 8, 2019 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvst/fa33b9dcb58040cbcb0ea376146d4e8c to your computer and use it in GitHub Desktop.
Save tvst/fa33b9dcb58040cbcb0ea376146d4e8c to your computer and use it in GitHub Desktop.
Hack to write to Streamlit app from another thread. See: https://discuss.streamlit.io/t/live-plot-from-a-thread/247
import streamlit.ReportThread as ReportThread
from streamlit.server.Server import Server
class ThreadSafeSt():
def __init__(self):
"""Object that write to a Streamlit app outside the main thread.
This object must be created from the main thread, and then passed
around to other threads so they can write to the Streamlit app.
Example
-------
>>> # This must be called from the main thread:
>>> thread_safe_st = ThreadSafeSt()
>>>
>>> def function_called_from_another_thread(arg1, arg2, st):
... st.main.markdown('arg1 is: %s' % arg1)
... st.sidebar.markdown('arg2 is: %s' % arg2)
>>>
>>> # On another thread:
>>> function_called_from_another_thread(10, 20, thread_safe_st)
"""
ctx = ReportThread.get_report_ctx()
self.main = ctx.main_dg
self.sidebar = ctx.sidebar_dg
@rmartin16
Copy link

not sure this works anymore.....v0.55.0

AttributeError: 'ReportContext' object has no attribute 'main_dg'

@TimMazhari
Copy link

not sure this works anymore.....v0.55.0

AttributeError: 'ReportContext' object has no attribute 'main_dg'

Have you found a solution for this?

@rmartin16
Copy link

i didn't seem to have this problem on v0.53.0 so i stayed there.

However, @jrhone wrote this gist to solve a different problem with a similar root problem.

@pikarpov
Copy link

It seems that they made it easier, hence this wrapper is now obsolete. Here is what seems to work for me:

from streamlit.ReportThread import add_report_ctx

# Your thread creation code:
thread = threading.Thread(target=runInThread, args=(onExit, PopenArgs))
add_report_ctx(thread)
thread.start()

Credit: @tim - https://discuss.streamlit.io/t/how-to-run-a-subprocess-programs-using-thread-inside-streamlit/2440

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