Issues with multiple files and real-time application

I am trying to develop a custom component that would get its data in real time while the script is running. Without going into too much detail my current approach is to create a WebSocket connection to a server using asyncio and send data to it.

My problem is while the asyncio loop is running the script cannot be stopped through streamlit’s stop button on the frontend nor by pressing Ctrl+C in the terminal, the only way to shut it down is to kill the streamlit app.

Right now all of my implementation of the code is written in the components init.py file, because I had a suspicion that seperating it into multiple files was the issue, but it didn’t solve the problem.

Now I’ve tried to write a code that produces the same results with minimal code, even taking asyncio out of the equations, and I found this interesting behaviour:

Consider this streamlit script:

from time import sleep

def test():
    i = 0
    while True:
        print(f"running {i}")
        i += 1
        sleep(2)
test()

If I run this script the message will be printed to the terminal. I can shut it down by using the stop button or by pressing Ctrl+C.

Now If I make the previus script into a seperate file called test.py (without calling the test function of course) and create a seperate script called app.py

app.py

from test import test

test()

The script will run, but it cannot be stopped. If I press the stop button on the frontend it will keep running, and I can’t shut it down from the terminal with Ctrl+C either.

Can anyone give some insight on what’s happening here? I believe the same thing causes my problem with the websocket connection.

Or maybe my inital approach is inherently wrong and there is a better approach?