Streamlit and asynchronous functions

I want run a function asynchronously and launch a streamlit dashboard.
So far I have done the following

### file launch_dashboard.py ####
import os
import asyncio
import streamlit.bootstrap
from datetime import datetime

dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'dummy.py')

args = []

async def do_some_iterations():
    for i in range(10):
        print(datetime.now().time())
        await asyncio.sleep(1)
    print('... Cool!')


async def main():
    task = asyncio.create_task (do_some_iterations())
    await task

asyncio.run(main())

streamlit.bootstrap.run(filename, '', args, flag_options={})
### file dummy.py ####
import streamlit as st  

title = st.title("Hello title.")

I am running the launch_dashboard.py script but I have to wait for the loop to finish to get the streamlit dashboad.
I would like instead to be able to open the dashboard with the loop is running.
Does anyone know how to do this please?

There is this post that looks kinda similar but the subprocess workaround will not work for me.

Any help greatly appreciated!

The awaitable task is not run concurrently as you might be expecting. It’s just being scheduled to run and will run like any sequential (blocking) function call. Try using loop.run_in_executor() (or concurrent.futures.ThreadPoolExecutor()) to run it in a thread. See this doc.

I haven’t tried myself, but you could wrap streamlit.bootstrap.run() in an awaitable task and run both tasks concurrently. See this doc.

If you get it working, please post your solution.

Cheers,
Arvindra

1 Like

Thanks but I couldnt really do it. This is how I changed my file; I am getting a RuntimeError: Cannot run the event loop while another loop is running exception. If by any change you have any ideas it will be masively apreciated!

Also, I couldnt understand the approach with executor, hence didnt do anything with this…

### file launch_dashboard.py ####
import os
import asyncio
import streamlit.bootstrap
from datetime import datetime
import nest_asyncio

nest_asyncio.apply()


async def do_some_iterations():
    for i in range(10):
        print(datetime.now().time())
        await asyncio.sleep(1)
    print('... Cool!')


async def main():
    task = asyncio.create_task(do_some_iterations())
    task2 = asyncio.create_task(load_dashboard())
    await task
    await task2

async def load_dashboard():
    print('Loading dashboard')
    dirname = os.path.dirname(__file__)
    filename = os.path.join(dirname, 'dummy.py')
    args = []
    streamlit.bootstrap.run(filename, '', args, flag_options={})
    print('Loaded.')


if __name__ == "__main__":
    asyncio.run(main())


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