How to run a subprocess programs using thread inside streamlit?

Hey @ITMSEC17, welcome to Streamlit!

Yeah, this isn’t well-documented in Streamlit. If you want to perform Streamlit calls from within threads you create, you need to attach a Streamlit “ReportContext” to those threads. (This is a bit of state that lets Streamlit know which user session the thread belongs to.)

Here’s how to attach a ReportContext to your thread. You should do this after creating the thread, and before starting it.

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()

I’ve opened a feature request to improve the error message!

4 Likes