How can a Python script detect whether is being run by streamlit?

I have a python script that sometimes I run by streamlit run and other times I run by python How can the script detect whether it was invoked by streamlit?

Hi @fredzannarbor,

Thanks for posting!

Can you explain further what you mean by detect?

I want to do a simple conditional.

if {launchedbystreamlit}:
    st.error("error message")
    print("error message")

Help me think this through…

streamlit run or

–are there any streamlit processes running on this machine?
– are any of those st processes running

Thet feels too complicated and fragile to me. It would be easier to query the state of the streamlit module (or some submodule). Unfortunately there is no public API for this as far as I know. The closest thing would be using _get_websocket_headers(). It is not public but there’s at least the promise of trying not to accidentally break it, which is more than what you get by using any other internal name. It curretly returns None if you script is running standalone.

1 Like

Close enough!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.