見出し画像

Streamlit standalone executable

Streamlit x pythonで作成した,appのexe作成メモ.参考は下のサイト.


手順

1.pycharmエディタで適当にプロジェクト作製.今回はstreamlit_standalone_executableというフォルダにvenvでプロジェクトを作成.

2.必要なパッケージのインストール.
・streamlit 1.4.0
・pyinstaller 4.1

3.任意のapp作成.今回は簡単な以下のコードをexeにする.
main.py

import streamlit as st

if __name__ == '__main__':
    st.header("Hello world")

4.streamlitパッケージのcli.pyを編集.
***\streamlit_standalone_executable\venv\Lib\site-packages\streamlit\cli.py
下記を追加.

def _main_run_clExplicit(file, command_line, args=[], flag_options={}):
    streamlit._is_running_with_streamlit = True
    bootstrap.run(file, command_line, args, flag_options)

5.run_main.pyを作成.

import streamlit.cli

if __name__ == '__main__':
    streamlit.cli._main_run_clExplicit('main.py', 'streamlit run')

6.streamlit_standalone_executableのフォルダ内にhooksというフォルダを作成し,hook-streamlit.pyを作成.

from PyInstaller.utils.hooks import copy_metadata
datas = copy_metadata('streamlit')

7.streamlit_standalone_executableのフォルダ内に.streamlitフォルダを作成し,config.tomlを作成.(textエディタで大丈夫)

[global]
developmentMode = false

[server]
port = 8501

8.pycharmエディタ内terminalから,下記でexeを作成.
pyinstaller --onefile --additional-hooks-dir=./hooks run_main.py --clean

9.ただpyinstallerを回しただけではできないので,8.の実行でできたrun_main.specのa = Analysis… のdatasを下記のように編集.

datas=[("{$YOURPYTHONENV}/Lib/site-packages/altair/vegalite/v4/schema/vega-lite-schema.json",
        "./altair/vegalite/v4/schema/"),
       ("${YOURPYTHONENV}/Lib/site-packages/streamlit/static","./streamlit/static")
       ]

10.再度下記で実行.
pyinstaller --onefile --additional-hooks-dir=./hooks run_main.spec --clean

11.distフォルダにできたrun_main.exeファイルは,それ自体では動かない..streamlitとmain.pyがrun_main.exeと同じディレクトリにないといけない.

12.exeを開けばstreamlitアプリが起動する.

run_main.pyによってmain.pyを実行しているという構造.main.pyを書き換えてもわざわざexeを作成する必要はない.(もちろんexeに含まれているパッケージのみ使用するという前提はある)

ディレクトリ構成

streamlit_standalone_executable/
    - .streamlit/
        - config.toml
    - hooks/
        - hook-streamlit.py
    - main.py
    - run_main.py
    - run_main.spec
    - build/
        - run_main/
            - many .toc and .pyz
    - dist/
        - run_main.exe

*run_main.exeと同一ディレクトリに.streamlitとmain.pyをいれることを忘れずに.

最後に

streamlitアプリを簡単にオフラインで共有したい場面には,ちょっと面倒だけど使えるかも.streamlitはどんどんアップデートしているので,これからもっと簡単にexe化できる方法がでると思う.


この記事が気に入ったらサポートをしてみませんか?