LoginSignup
1
5

More than 1 year has passed since last update.

pyinstaller --onefile で固めた.exeで、実行時に動的にモジュールをimportする

Last updated at Posted at 2020-07-09

Python公式では非推奨だが、成果物を人に渡す時に、以下のような config.py を、 main.py と同階層に置いて、mian.py でインポートしてそのまま使ったりすることがあった。

config.py
width = 10
height = 10
count = 100
threshold = 50
main.py
from config import *

今回pyinstallerで固めた.exeからも、動的に外部のパラメータをimportするようにしたかったのだが、ハマったのでTIPSをメモしておく。

まず、こちらの記事が非常に参考になった。
(参考) https://ja.coder.work/so/python/1422895

普通に.exeにしたものは、importlibを使えば動的にimportしてくれるのだが、 --onefile で固めると、config.pyも内部に取り込まれてハードコーディングされる模様。
この問題に関しては、(泥臭い方法だが)とりあえず.exe化するときに config.py を消しておくことで対応した。(おそらく --hidden-import とかを使って.specファイルを編集して~みたいなのが正しい手順)

あとは main.py 内で

main.py
import os
import sys
import importlib

sys.path.append(os.path.join(os.path.dirname(__file__), '.'))

config = importlib.import_module('config')

width = config.width
height = config.height
count = config.count
threshold = config.threshold

としてカレントディレクトリをパスに加えてからimportしてやればOK。

1
5
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
1
5