简体   繁体   English

如何从 Python 脚本中运行 Streamlit 应用程序?

[英]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:有没有办法从 python 脚本中运行命令streamlit run APP_NAME.py ,可能类似于:

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 .由于我正在处理的项目需要跨平台(和打包),我不能安全地依赖对os.system(...) subprocess调用。

Hopefully this works for others: I looked into the actual streamlit file in my python/conda bin, and it had these lines:希望这对其他人有用:我查看了我的 python/conda bin 中的实际流光文件,它有以下几行:

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:从这里,您可以看到在命令行上运行streamlit run APP_NAME.py与(在 python 中)相同:

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.所以我把它放在另一个脚本中,然后运行该脚本从 python 运行原始应用程序,它似乎工作。 I'm not sure how cross-platform this answer is though, as it still relies somewhat on command line args.我不确定这个答案有多跨平台,因为它仍然在某种程度上依赖于命令行参数。

You can run your script from python as python my_script.py :您可以从 python 作为python my_script.py运行您的脚本:

import sys
from streamlit import cli as stcli
import streamlit
    
def main():
# Your streamlit code

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

I prefer working with subprocess and it makes executing many scripts via another python script very easy.我更喜欢使用子进程,它使通过另一个 python 脚本执行许多脚本变得非常容易。

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')])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM