【问题标题】:How Can I Run a Streamlit App from within a Python Script?如何从 Python 脚本中运行 Streamlit 应用程序?
【发布时间】:2020-10-26 20:45:46
【问题描述】:

有没有办法在 python 脚本中运行命令 streamlit run APP_NAME.py,可能类似于:

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


由于我正在进行的项目需要跨平台(和打包),我不能安全地依赖对os.system(...)subprocess 的调用。

【问题讨论】:

    标签: python streamlit


    【解决方案1】:

    希望这对其他人有用: 我查看了我的 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())
    

    从这里,你可以看到在命令行上运行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())
    

    所以我把它放在另一个脚本中,然后运行该脚本以从 python 运行原始应用程序,它似乎工作。我不确定这个答案有多跨平台,因为它仍然在某种程度上依赖于命令行参数。

    【讨论】:

      【解决方案2】:

      您可以在 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())
      

      【讨论】:

        【解决方案3】:

        我更喜欢使用子进程,它使通过另一个 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')])
        

        【讨论】:

          猜你喜欢
          • 2017-01-01
          • 2021-03-07
          • 1970-01-01
          • 2011-03-16
          • 2023-01-30
          • 2021-01-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多