Warning for missing ScriptRunContext

Hi to all…when i am running my streamlit app in Pycharm i get this warning

missing ScriptRunContext! This warning can be ignored when running in bare mode.

other than this warning appearing in the terminal 100 times the app works fine…
can anyone explain why this warning occurs…
Thanks in advance

Bumping this. Very annoying, but app (in my case, a test) works fine.

I’ve tried suppressing the logging with logging.getLogger('streamlit').setLevel(logging.ERROR) but it doesn’t help.

Any ideas?

What if you run it without pycharm?

are you running it in a jupyter notebook?

I’m running it in VSCode so it’s not exclusive to the IDE you’re using. I wish I could at least learn what “bare mode” even means.

Alright I think I’ve got my case figured out at least. This is what worked for me:

from streamlit.runtime.scriptrunner import add_script_run_ctx,get_script_run_ctx
from subprocess import Popen

ctx = get_script_run_ctx()
##Some code##
process = Popen(['python','my_script.py'])
add_script_run_ctx(process,ctx)

My interpretation of the error is that streamlit does not like streamlit function calls outside the main controlling script, so if you launch your script with streamlit run script.py and try to use st.write or other functions in another script that the main script.py calls using multithreading or subprocess, then we get the error. To suppress the error, we just need to add it to the context to make streamlit happy again. The documentation only refers to multithreading, but subprocess also works for me. I’m not sure if multiprocess would have similar behavior, but in theory I think it would. I have not tested it though.

Lots of people seem to be trying (myself included) only add_script_run_ctx(process) without much success. For me, the key was I needed to also supply the ctx to which it would add the script, so that’s why we instantiate it at the top of the script. After that, you just add the script to the context manager like we’ve been trying in order to suppress the annoying error spam.

Further, the “bare mode” it refers to is used for script/streamlit testing without launching the script via the streamlit CLI method, so for most of us it seems we would have to deal with it eventually since we wouldn’t want to deploy in bare mode.

2 Likes

No…from the answer that Talia posted, i am assuming that i use many imports that i execute in the main script and maybe that is causing the warnings!

Hi…i actually have functions that i export and execute in the main script that return a plotly figure and then i just use st.plotly_chart to plot it…in some cases i export a function that calculates x and then use it in the function that returns the plotly figure and then i use that in the main script!

In my case, when my script starts other threads and runs streamlit functions within them, this warning appears.
When I try to avoid running st functions in other threads (including avoid running functions decorated with @st.cache_resource), this warning disappears.

Has anyone found a general solution for this ScriptRunContext warning? In my Streamlit app, it’s showing up around 50 times, which is pretty annoying. I have not trying to resolve it, the app runs fine but seems to come from Marker-pdf between each pdf conversion or it is somehow related to the file upload

There will be a guide on this soon, but basically, multithreading isn’t officially supported. You have two options:

  1. Don’t call Streamlit commands within a thread or subprocess you created. Instead, get the results from the thread in memory and use Streamlit commands within the parent script/page to handle any Streamlit commands (including Session State calls).
  2. (Very unsupported, could change at any time, and possible to introduce security vulnerabilities:) Add Streamlit’s script context to your thread. (I’m looking to see if this is also possible for processes.)
import streamlit as st
from streamlit.runtime.scriptrunner import add_script_run_ctx, get_script_run_ctx
import time
from threading import Thread


class WorkerThread(Thread):
    def __init__(self, delay, target):
        super().__init__()
        self.delay = delay
        self.target = target

    def run(self):
        # runs in custom thread, but can call Streamlit APIs
        start_time = time.time()
        time.sleep(self.delay)
        end_time = time.time()
        self.target.write(f"start: {start_time}, end: {end_time}")


delays = [5, 4, 3, 2, 1]
result_containers = []
for i, delay in enumerate(delays):
    st.header(f"Thread {i}")
    result_containers.append(st.container())

threads = [
    WorkerThread(delay, container)
    for delay, container in zip(delays, result_containers)
]
for thread in threads:
    add_script_run_ctx(thread, get_script_run_ctx())
    thread.start()

for thread in threads:
    thread.join()

st.button("Rerun")

(This example might get refined a bit further before being published in the docs. I might add more protections to the example to prevent stray threads from lingering, especially if a script is interrupted by a user before the page runs completely.)

Hi Debbie, I tried your solution, but I was not able to get it working. If you have time, I will link the repo: GitHub - flight505/Lightrag_test_app

It is a Streamlit wrapper for Lightrag with added layers for metadata, equations, references, in-line citations, and so on. The PDF conversion is using Marker-pdf, which is using Apple MPS. I think Marker is causing the warning. It will likely only run on Mac at this point, but you can set the GPU to auto if you are not on Apple Silicon. To run it, you can use UV, and this one line: uv run streamlit_app.py && streamlit run streamlit_app.py to create a temp environment and run the app.

if this helps anyone, i was running several pytests that had some streamlit coupled in… these errors drove me crazy… this fixed it… put into my tests/ folder

#__init__.py 
import logging
import sys
from unittest.mock import MagicMock

# Mock Streamlit modules to prevent warnings
mock_module = MagicMock()
mock_module.get_script_run_ctx = lambda: None
sys.modules['streamlit'] = mock_module
sys.modules['streamlit.runtime'] = mock_module
sys.modules['streamlit.runtime.scriptrunner_utils'] = mock_module

def pytest_configure(config):
    """Configure logging based on pytest command line options"""
    log_cli_level = config.getoption('--log-cli-level', None)
    
    # Set up root logger with console handler
    root_logger = logging.getLogger()
    console_handler = logging.StreamHandler(sys.stdout)
    
    # Set log level based on pytest options
    level = logging.INFO if log_cli_level == 'INFO' else logging.WARNING
    root_logger.setLevel(level)
    console_handler.setLevel(level)
    
    # Add handler to root logger
    root_logger.addHandler(console_handler)

A workaround is to edit the local copy of the library: .venv/lib/python3.12/site-packages/streamlit/runtime/scriptrunner_utils/script_run_context.py, and change:

def get_script_run_ctx(suppress_warning: bool = False) -> ScriptRunContext | None:

to

def get_script_run_ctx(suppress_warning: bool = True) -> ScriptRunContext | None:

It will be overwritten in updates. Meanwhile, no annoying messages will be displayed.