0
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 2024-10-23

概要

PyInstallerでPythonスクリプトをexe化すると、ファイルの参照方法が変わるようです。

通常の.pyファイルでは__file__を使って実行中のスクリプトのパスを取得できますが、exe化した場合にはsys.executableで実行ファイルのパスを取得しないと、同じフォルダに置いてあるファイルを参照できなくなるようでした。

対策法

これを防ぐために、以下のコードで自分がPyInstallerで実行されているかどうかを判別する必要がありました。

import os
import sys


def fetch_base_path() -> str:
    """基準パスを取得する関数"""
    # PyInstallerで実行されているかどうかをチェック
    if getattr(sys, "frozen", False):
        # EXEの実行ファイルのパスを取得
        return os.path.dirname(sys.executable)
    else:
        # スクリプトの実行ファイルのパスを取得
        return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        
# 使用例
# ベースパスを取得
#base_path = fetch_base_path()
0
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
0
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?