How to check if code is run inside streamlit (and not e.g. IPython)

Is there a way to check if some python code is run from streamlit, in contrast to e.g. IPython or Jupyter Notebook?

I’m looking for a functionality similar to this, which returns True if run inside a Jupyter Notebook:

def isnotebook():
    try:
        shell = get_ipython().__class__.__name__
        if shell == 'ZMQInteractiveShell':
            return True   # Jupyter notebook or qtconsole
        elif shell == 'TerminalInteractiveShell':
            return False  # Terminal running IPython
        else:
            return False  # Other type (?)
    except NameError:
        return False      # Probably standard Python interpreter

https://stackoverflow.com/a/39662359/2336056

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.

Hi @jgieseler :wave:

I’m not sure what the correct method is to ascertain whether some script.py was run via streamlit run script.py or python script.py.

However, here’s how I do it. If ctx below returns None, I infer the script was run with python script.py. Else, it was run using streamlit run:

# script.py
import streamlit as st
from streamlit.script_run_context import get_script_run_ctx

ctx = get_script_run_ctx()

print(ctx)

Best,
Snehan

3 Likes

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
1 Like

maybe a bit more explicit for checking None? (and a bit shorter :slight_smile:)

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
3 Likes

Well, it seems this function is not working anymore as of today (i.e., with streamlit version 1.9.0). :frowning:

The codebase was updated since the last release.

Now, you’ve got to do:

from streamlit.scriptrunner import get_script_run_ctx
1 Like

Thanks again @snehankekre, that did the trick!

So the function should now look like this:

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? :roll_eyes:

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
1 Like

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