How can I invoke streamlit from within python code?

Hello Folks,

What is the best means to invoke streamlit from within python code ?
I dont want to go via the CLI route of streamlit run <script-name.py>

This link has some reference, but again to invoke as mentioned in link, python click context is needed.

Thankyou
Jacob

Looks like this is a way:

import os
import streamlit.bootstrap
from streamlit import config as _config

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

_config.set_option("server.headless", True)
args = []

#streamlit.cli.main_run(filename, args)
streamlit.bootstrap.run(filename,'',args)
3 Likes

Thanks for the helpful tips! That’s what I was trying to find.

By the way, when I ran your code, I saw the following error.

TypeError: run() missing 1 required positional argument: 'flag_options'

Instead, I had to write as following. This may be due to a different version of Streamlit. (I’m using Streamlit version 0.86.0.)

streamlit.bootstrap.run(filename, '', args, flag_options={})

In anyway, thanks again for the tips!

Regards,
Atsushi

Hi, i figured when i start streamlit with bootstrap, it will break forms. As long as I run the code from command line, everything works. When I invoke streamlit from within python, forms are broken.

I opened an issue here.

Feel free to add if you have any thoughts about it.

For those who are interested in this feature,

streamlit.bootstrap has been moved to streamlit.web.boostrap.

You can also do

import sys
from streamlit.web import cli as stcli

if __name__ == '__main__':
    sys.argv = ["streamlit", "run", "APP_NAME.py"]
    sys.exit(stcli.main())

Source:

Official supported & recommended way is via cli.

streamlit run your_app.py

But still, if you prefer to render the app from within python, in st 1.30 is

from streamlit import config as _config
from streamlit.web.bootstrap import run
_config.set_option("server.headless", True)
run('your_app.py', args=[], flag_options=[], is_hello=False)

But this could change from one release to another (as it’s not officially supported)