pyinstaller로 작성한 exe파일의 현재 디렉토리 취득 오류

python post logo 파이썬
스폰서 링크

python명령으로 잘 실행되던 test.py 소스를 [python 소스를 exe실행파일 만들기] 방법으로 컴파일해서 test.exe로 실행하면 현재 작업 디렉토리를 취득하는 처리에서 오류가 발행하는 경우가 있습니다.

import os
import sys
#python test.py로 실행한 경우,test.py를 보관한 디렉토리의 full path를 취득
program_directory = os.path.dirname(os.path.abspath(__file__))
#현재 작업 디렉토리를 변경
os.chdir(program_directory)
... 이하 생략...
 환경파일 내용의 로드처리에서 오류 발생...

이 경우 다음과 같이 getattr(sys, ‘frozen’, False)의 조건문을 사용하여 exe파일은 sys.executable, py파일은 __file__를 사용해 각각의 경우에 따라 다른 방법으로 풀 패스를 취득하여 현재 작업 디렉토리를 변경해줌으로써 오류를 해결할 수 있습니다.

import os
import sys
if getattr(sys, 'frozen', False):
    #test.exe로 실행한 경우,test.exe를 보관한 디렉토리의 full path를 취득
    program_directory = os.path.dirname(os.path.abspath(sys.executable))
else:
    #python test.py로 실행한 경우,test.py를 보관한 디렉토리의 full path를 취득
    program_directory = os.path.dirname(os.path.abspath(__file__))
#현재 작업 디렉토리를 변경
os.chdir(program_directory)
... 이하 생략...

제목과 URL을 복사했습니다