3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pyinstallerで作成したexeにおけるカレントディレクトリの変更

Last updated at Posted at 2022-08-24

はじめに

pyinstallerで作成したexeは、カレントディレクトリがよくわからないことになることがある気がする。
exeファイルと同階層に、設定ファイルを置いたりログファイルを出力させたいなど、どうしても当該プログラムに対する相対パスを使いたいときに、カレントディレクトリをいい感じにしたいです。
ただ、__file__とかを使ってもうまく行きませんし、他の記事みても一発ではうまく行かなかったので自分のためにメモ。

解決方法

実装例

#pathlibを使う場合
import os
import sys
import pathlib
os.chdir(pathlib.Path(sys.argv[0]).resolve().parent)

#osモジュールだけで済ます場合
import os
import sys
os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

解説

キーとなる知識

sys.argv[0]に、「実行するexeファイル自身の相対パス」が文字列として代入されている

やること

Pathlibモジュールにしてもosモジュールにしても手順は一緒

  • sys.argv[0]に代入されている"相対パス"を"絶対パス"に変換する
    • Pathlibの場合…exePath = pathlib.Path(sys.argv[0]).resolve()
    • osの場合…exePath = os.path.abspath(sys.argv[0])
  • 上述の絶対パスはexeファイル自身なので、"親ディレクトリの絶対パス"を編み出す
    • Pathlibの場合…exeDir = exePath.parent
    • osの場合…exeDir = os.path.dirname(exePath)
  • カレントディレクトリをos.chdir(dir)で変更する

おわりに

ちなみに、sys.argv[1]以降には、コンソール等からexeファイルを実行するときに引数として渡した文字列が代入されるらしい。
もしくは、exeファイルに何かしらのファイルをドラッグアンドドロップすることでexeファイルを実行した場合は、ドラッグアンドドロップしたファイルのパスが代入されるらしい。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?