py2exeでpythonコードをexe化


追記

この記事で書いたsetup.pyを使う方法は、今後使えなくなる可能性があります(version 0.13.0.0で削除)。
公式の推奨手順は以下のリンクを参照のこと
https://github.com/py2exe/py2exe/blob/master/docs/migration.md
https://github.com/py2exe/py2exe/blob/master/docs/py2exe.freeze.md




エラーが出たので書いておきます。


windowspythonをダウンロード
ここでMicrosoftストアからダウンロードするとうまく行かないようです(自分でPATHを通せばいいんだろうけど、py2exeにPATHを通しただけではダメで、他にどこにPATHを通せばいいのか分からなかった)。

python公式ページからインストーラーをダウンロードし、インストール時に"Add Python 3.x to PATH"にチェックを入れるとうまく行きます。


・setup.pyを作成
exe化したいpyファイルと同じディレクトリに、"setup.py"という名前のファイルを作る。

from distutils.core import setup
import py2exe
#ここで、pyファイル内でimportしたモジュールもimportする必要がある

setup(console=['(exe化したいファイル).py'])
#GUIがある場合は「console=」ではなく「windows=」と書く

少しハマった点があったので書いておきました。


・実行

python setup.py py2exe

これで上手くいけば、作成されたdistフォルダ内にexeファイルがあるはずです。



なお、近々この方法は使えなくなるらしいです。
GitHub - py2exe/py2exe: Create standalone Windows programs from Python code
Using a setup.py script or the builder

Using a setup.py script with py2exe is deprecated. Please adapt your scripts to use the new freeze API. This interface will be removed in the next major release.

The build_exe (or -m py2exe) CLI was removed in version 0.13.0.0.