LoginSignup
6
7

More than 1 year has passed since last update.

【Pyinstaller】MacOS用、Windows用のexeをそれぞれ作成する失敗しない方法

Last updated at Posted at 2023-02-01

はじめに

Pyinstallerを使ったPythonスクリプトのexe化方法を紹介します。
Pyinstallerは、Macで動かす場合はMacOS上で作成、WindowsならWindows上で作成、というように、動かしたいOS上でそれぞれ作成する必要があります。
それぞれのOSで失敗せずに作成できるコマンドなども合わせてご紹介します。

exeを作成する

1. 仮想環境を作成する

Pyinstallerでexe化する際、仮想環境外でexe化をするとPC上にpipでインストールされている全てのライブラリを含んでしまいます。仮想環境でexe化することで、軽量なexeファイルを作成できます。

ディレクトリ構成は以下のようにします。

MyProject
 └─ my_app
     └─app.py  <--exe化対象のスクリプト

ターミナルでMyProjectに移動し、仮想環境を作成します。

terminal
$ cd MyProject
$ python -m venv .venv

MyProject直下に.venvが作成されたことを確認してください。

MyProject
 └─.venv
     ├─Include
     ├─Lib
     └─Scripts
 └─ my_app
     └─app.py  <--exe化対象のスクリプト

2. Pyinstallerをpipでインストールする

仮想環境に入ります。

terminal
MacOSの場合
$ source .venv/bin/activate

Windowsの場合
$ .venv¥Scripts¥activate

仮想環境に入ると以下のようになります。
(.venv) C:xxx/MyProject>

Pyinstallerをインストールします。

terminal
$ pip install pyinstaller

他にスクリプト内で使用しているライブラリがある場合は、そちらも全てインストールします。
requirements.txtを使用すると、一括でインストールすることができます。(ここでは説明を割愛します。調べるとやり方が出てきますので、見てみてください)

temrinal
pipでひたすらインストール
$ pip install aaaaa
$ pip install bbbbb
:
:

requirements.txtで一括インストール
$ pip install -r requirements.txt

3. Pyinstallerでexe化

MacOSの場合

terminal
$ pyinstaller -F my_app/app.py

Windowsの場合

terminal
$ pyinstaller my_app¥app.py --onefile

successfullyの文字が最後に出たら、exeの作成成功です!

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7