pythonstreamlit

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.


Solution

  • 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.