The background is that I want to have some python code that can be run as a Jupyter Notebook or as a streamlit app. Because I produce a figure with matplotlib, I need to either call plt.show() or st.pyplot(). The checking I ask for should make the decision where to “send” the figure to.
Thanks a lot @snehankekre, that is already a good idea! I modified it a bit so that it can be used if streamlit is not installed at all, and put it into a function that returns True when run within streamlit (and else False):
def check_streamlit():
"""
Function to check whether python code is run within streamlit
Returns
-------
use_streamlit : boolean
True if code is run within streamlit, else False
"""
try:
from streamlit.script_run_context import get_script_run_ctx
if not get_script_run_ctx():
use_streamlit = False
else:
use_streamlit = True
except ModuleNotFoundError:
use_streamlit = False
return use_streamlit
maybe a bit more explicit for checking None? (and a bit shorter )
def check_streamlit():
"""
Function to check whether python code is run within streamlit
Returns
-------
use_streamlit : boolean
True if code is run within streamlit, else False
"""
try:
from streamlit.script_run_context import get_script_run_ctx
return get_script_run_ctx() is not None
except ModuleNotFoundError:
return False
def check_streamlit():
"""
Function to check whether python code is run within streamlit
Returns
-------
use_streamlit : boolean
True if code is run within streamlit, else False
"""
try:
from streamlit.scriptrunner import get_script_run_ctx
if not get_script_run_ctx():
use_streamlit = False
else:
use_streamlit = True
except ModuleNotFoundError:
use_streamlit = False
return use_streamlit
Or in @Abdelgha_4’s form (haven’t checked it though):
def check_streamlit():
"""
Function to check whether python code is run within streamlit
Returns
-------
use_streamlit : boolean
True if code is run within streamlit, else False
"""
try:
from streamlit.scriptrunner import get_script_run_ctx
return get_script_run_ctx() is not None
except ModuleNotFoundError:
return False
sigh, why does the location of get_script_run_ctx has to change with every new release?
So with the current version of streamlit, the function needs to look like this (only thing that changed is the import):
def check_streamlit():
"""
Function to check whether python code is run within streamlit
Returns
-------
use_streamlit : boolean
True if code is run within streamlit, else False
"""
try:
from streamlit.runtime.scriptrunner import get_script_run_ctx
if not get_script_run_ctx():
use_streamlit = False
else:
use_streamlit = True
except ModuleNotFoundError:
use_streamlit = False
return use_streamlit