David
David

Reputation: 677

How Can I Run a Streamlit App from within a Python Script?

Is there a way to run the command streamlit run APP_NAME.py from within a python script, that might look something like:

import streamlit
streamlit.run("APP_NAME.py")


As the project I'm working on needs to be cross-platform (and packaged), I can't safely rely on a call to os.system(...) or subprocess.

Upvotes: 28

Views: 50394

Answers (7)

sglbl
sglbl

Reputation: 617

Since the developers changed the path again and the other answers don't work anymore:

if __name__ == "__main__":
    import subprocess
    from streamlit import runtime
    if runtime.exists():
        main()
    else:
        process = subprocess.Popen(["streamlit", "run", "src/main.py"])

Upvotes: 0

Jiri Dobes
Jiri Dobes

Reputation: 109

You can run your script from python as python my_script.py:

from streamlit.web import cli as stcli
from streamlit import runtime
import sys

if __name__ == '__main__':
    if runtime.exists():
        main()
    else:
        sys.argv = ["streamlit", "run", sys.argv[0]]
        sys.exit(stcli.main())

Upvotes: 10

Harshit Singhai
Harshit Singhai

Reputation: 1280

import sys
from streamlit.web import cli as stcli

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

Upvotes: 2

Ucl
Ucl

Reputation: 1

A workaround I am using is the following:

  1. Write the streamlit app to the temporary directory of the computer.
  2. Extecute the streamlit app.
  3. Remove the streamlit app again.
import os
import subprocess
import tempfile

def run_streamlit_app(app):
    # create a temporary directory
    temp_dir = tempfile.TemporaryDirectory()
    temp_file_path = os.path.join(temp_dir.name, 'app.py')
    
    # write the streamlit app code to a Python script in the temporary directory
    with open(temp_file_path, 'w') as f:
        f.write(app)
    
    # execute the streamlit app
    try:
        # execute the streamlit app
        subprocess.run(
            ["/opt/homebrew/Caskroom/miniforge/base/envs/machinelearning/bin/streamlit", "run", temp_file_path],
            stderr=subprocess.DEVNULL
        )
    except KeyboardInterrupt:
        pass
    
    # clean up the temporary directory when done
    temp_dir.cleanup()

where an example could look like the following:

app = """
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np

arr = np.random.normal(1, 1, size=100)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)

st.pyplot(fig)
"""
run_streamlit_app(app)

Upvotes: 0

Jan
Jan

Reputation: 675

With the current streamlit version 1.21.0 the following works:

import streamlit.web.bootstrap
streamlit.web.bootstrap.run("APP_NAME.py", '', [], [])

Execute ?streamlit.web.bootstrap.run do get more info on the different options for streamlit.web.bootstrap.run. For example, you can provide some args to the script.

Upvotes: 5

Subir Verma
Subir Verma

Reputation: 423

I prefer working with subprocess and it makes executing many scripts via another python script very easy.

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

import subprocess
import os

process = subprocess.Popen(["streamlit", "run", os.path.join(
            'application', 'main', 'services', 'streamlit_app.py')])

Upvotes: 7

David
David

Reputation: 677

Hopefully this works for others: I looked into the actual streamlit file in my python/conda bin, and it had these lines:

import re
import sys
from streamlit.cli import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

From here, you can see that running streamlit run APP_NAME.py on the command line is the same (in python) as:

import sys
from streamlit import cli as stcli

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

So I put that in another script, and then run that script to run the original app from python, and it seemed to work. I'm not sure how cross-platform this answer is though, as it still relies somewhat on command line args.

Upvotes: 28

Related Questions