LoginSignup
2
1

More than 1 year has passed since last update.

pythonのEXE化時のパスについて

Last updated at Posted at 2022-04-16

pyinstaller使用時のpathについて

pyinstallerで実行ファイル化すると、動作としてテンポラリフォルダ(_MEI*****というフォルダ)に解凍し、そこで実行する挙動になっています。

pyinstallerを使用して一つの実行ファイル化するときに、画像や設定等のファイルを参照する方法は2つあります。
実行ファイルがそれぞれ C:\python\にあるとします。
1.実行ファイルと同じフォルダに置いて参照する
2.ファイルを内蔵して参照する

1.実行ファイルと同じフォルダに置いて参照する場合

get_path.py
import sys
import os
get_path =  os.path.dirname(sys.argv[0])
必要によって .replace("\\" ,"/") を追加
print("get_path=",get_path)   #get_dir= C:\python

2.ファイルを内蔵して参照する場合

実際はテンポラリフォルダ内を参照することになるので、そのパスを取得します。

temp_path.exe
import sys
import os
temp_path = os.path.dirname(os.path.abspath(__file__))
print("temp_path=",temp_path)    #temp_path= C:\windows\temp\_MEI*****
※実行ファイル化した後での出力の結果です。パスはあくまで例です。

とりあえずこんな感じでできます。
コードを書く際、内蔵するか否か、最初に決めておかないといけないですね。
そういう意味では、最初の設計はやはり大事です。

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