본문 바로가기

Python

pyinstaller로 빌드된 파이썬 프로그램에서 리소스 경로 가져오기

728x90

파이썬으로 개발을 하는 사람 중 개발한 서비스나 앱을 pyinstaller로 배포하는 경우가 있을 수 있다.

 

다만 pyinstaller로 빌드한 제품은 스크립트로 실행하는 것과 달리 리소스나 에셋 파일을 가져올 때 경로가 달라지므로 이에 대응하는 함수가 필요하다.

 

pyinstaller로 빌드된 앱에서 리소스를 가져오는 방법은 다음과 같이 작성할 수 있다.

 

from typing import Union
import sys
from pathlib import Path


def get_asset_path(relative_path: Union[str, Path]):
    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
        bundle_dir = Path(sys._MEIPASS)
    else:
        bundle_dir = Path(__file__).parent

    return bundle_dir / relative_path

 

pyinstaller의 기본 옵션으로 빌드된 앱은 sys.frozen의 값이 True를 가지고 리소스 파일은 _MEIPASS라는 폴더 내에 저장된다.

 

따라서 getattr()과 hasattr() 함수로 pyinstaller로 빌드된 앱인지 확인할 수 있고, 확인 결과에 따라 앱의 루트 디렉터리인 bundle_dir를 결정할 수 있다. 

 

그 이후는 나머지 상대 경로를 지정해서 원하는 리소스를 가져올 수 있다.

728x90