pywinautoを用いたプログラムをexe化する時にハマった


先日のWindows10でpywinautoを使おうとしたらハマったの続きのような記事です。

WindowsのGUI自動化ライブラリのpywinautoを用いたプログラムをPythonで開発し、exe化する時にうまくいかなかったのでメモ。

初めて英語のIssueをまともに読みましたがメチャクチャ疲れますね...

環境

  • Windows10(64bit)
  • Python 3.6.4(32bit)
  • pyinstaller 3.3.1
  • pywinauto 0.6.4

内容

以下のテストプログラムをexe化する。メモ帳を開くだけのプログラム。

note.py
from pywinauto.application import Application

app = Application().start("notepad.exe")

exe化せずに実行してみる。

C:\Users\user\Desktop>python note.py

問題なく起動した。

ハマったところ

次にこのファイルをexe化して実行してみる。

C:\Users\user\Desktop>pyinstaller --onefile note.py

C:\Users\user\Desktop>cd dist

C:\Users\user\Desktop>note.exe
.
.
.
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Admin\\AppData\\Local\\Temp\\_MEI157682\\comtypes\\gen\\_944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.py'
[15668] Failed to execute script note

このようなエラーが発生して、うまく動作しない。

解決策

調べてみるとPyInstallerにこんなIssueがあった。
PyInstaller 3.3.1 does not work with Pywinauto lib import #3177

エラー内容を見る感じこの人も同じようなエラーが起きている様子。
一番下まで読み進めて行くと、こんなことが書いてあった。

Just now I fixed this @korniichuk

Create folder comtypes/gen/ in the same folder of your test.py, and copy file _944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.py and UIAutomationClient.py (under Lib/site-packages/comtypes/gen/) into this folder.

Then use pyinstaller --hidden-import comtypes.gen._944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0 --hidden-import comtypes.gen.UIAutomationClient test.py

Good luck

内容は、
test.pyと同じディレクトリにcomtypes/genというディレクトリを作成し、その中にfile _944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.pyUIAutomationClient.py(Lib/site-packages/comtypes/gen/の中にある)をコピーして、pyinstaller --hidden-import comtypes.gen._944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0 --hidden-import comtypes.gen.UIAutomationClient test.pyで実行したらいけるで。がんばれ。
とのこと。

今回の内容に沿って説明すると、デスクトップにnote.pyを作成しているのでデスクトップにcomtypes/gen作成してpyinstaller --hidden-import comtypes.gen._944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0 --hidden-import comtypes.gen.UIAutomationClient note.pyで問題なく実行することができた。