環境
- Python 3.12.4
- Poetry 1.8.3
- pyinstaller 6.10.0
背景
Pythonで作成したツールを、Windows用の実行ファイルとして提供したいです。
GitHubでリリースページを公開したら、Pyintallerで生成した実行ファイルをReleaseページへアップロードするようにしました。
自分用のメモとして、必要な設定ファイルを記事に残しておきます。
Python関係のファイル
$ tree
.
├── pyproject.toml
├── sample
│ ├── __init__.py
│ ├── __main__.py
│ ├── data
│ │ └── logging.yaml
│ └── utils.py
pyproject.toml
[tool.poetry]
name = "sample"
version = "0.1.0"
description = ""
authors = ["yuji38kwmt"]
[tool.poetry.dependencies]
python = "^3.12"
pyyaml = "*"
[tool.poetry.group.publish]
# pyinstallerは通常時の開発では不要なのでオプショナルに設定
optional = true
[tool.poetry.group.publish.dependencies]
pyinstaller = { version = "^6.10", python = "=3.12" }
[tool.poetry.scripts]
sample = "sample.__main__:main"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
__main__.py
import logging
from sample.utils import load_logging_config
logger = logging.getLogger(__name__)
def main():
load_logging_config()
logger.info("hello world")
if __name__ == "__main__":
main()
utils.py
import logging.config
import yaml
import pkgutil
def load_logging_config() -> None:
data = pkgutil.get_data("sample", "data/logging.yaml")
logging_config = yaml.safe_load(data.decode("utf-8"))
logging.config.dictConfig(logging_config)
以下は、ツールを実行した結果です。
$ poetry run sample
INFO : 2024-08-21 14:58:19,858 : sample.__main__ : hello world
Pyintallerの設定
以下のコマンドで、実行ファイルを生成しています。
PS> poetry run pyinstaller sample/__main__.py --name sample --add-data "sample/data/:sample/data"
-
--name sample
:このオプションを指定しないと、__main__.exe
という実行ファイルが生成されます。名前が分かりにくいので、sample.exe
という実行ファイルが生成されるようにしました。 -
--add-data "sample/data/:sample/data"
:ログの設定ファイルが実行ファイルに含めるためのオプションです。このオプションを指定しないと、logging.yaml
が見つからないというエラーが発生します。
Github Actions
.github/workflows/publish-exe-file
name: publish executable file to release page
# releaseページにWindows用の実行ファイルをアップロードする。windowsはpython環境の構築に少し手間がかかるので、実行可能ファイルを用意する。
on:
release:
types:
- published
permissions:
contents: write
jobs:
build-and-release:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: 3.12
- name: Install Poetry and dependencies
run: |
python -m pip install --upgrade pip "poetry<1.9"
poetry install --only main,publish
- name: Create executable file with pyinstaller and zip
run: |
poetry run pyinstaller sample/__main__.py --name sample --add-data "sample/data/:sample/data"
pushd dist
Compress-Archive -Path sample -DestinationPath sample-windows.zip
popd
- name: Upload a executable file to GitHub Releases
uses: softprops/action-gh-release@v2
with:
files: |
dist/sample-windows.zip
GitHubでリリースページを作成すると、sample-windows.zip
というファイルが"Assets"に追加されます。
以下は、sample-windows.zip
にあるsample.exe
を実行した結果です。
PS > .\sample\sample.exe
INFO : 2024-08-21 15:25:32,973 : __main__ : hello world