카테고리 없음
python 예제 - 프로그램 실행 위치 확인 방법 3종 - os.getcwd, __file__, sys.argv
gomming
2021. 3. 2. 23:41
#workingdirectory #python #작업경로확인 #설치경로확인 #실행위치확인
현재 위치 확인 방법
working directory 확인
>>> import os
>>> os.getcwd()
'c:\\py_gom'
os.getcwd() 명령어로 쉽게 확인 가능하다.
py 파일 위치 확인하기
설치경로 확인
스크립트 파일의 실행 경로를 얻어 설치 경로로 활용하는 방법이 있다.
여러 방법으로 실행 경로를 확인할 수 있다.
import os
print (os.path.abspath(__file__))
결과 -> c:\py_gom\test1.py
이렇게 __file__ 을 통해 확인할 수 있다.
실행 파일의 경로만 분리해기
import os
INSTALL_PATH = os.path.dirname(os.path.abspath(__file__))
print (INSTALL_PATH)
결과 -> c:\\py_gom
또다른 방법
sys.argv
import os, sys
#INSTALL_PATH = os.path.dirname(os.path.abspath(__file__))
INSTALL_PATH = os.path.dirname(sys.argv[0])
print (sys.argv[0]+'\n'+INSTALL_PATH)
결과->
c:\py_gom\test1.py
c:\py_gom
sys.arg[0] 명령어는 python으로 실행한 시스템 argument를 확인할 수 있다.
cmd에서 python c:\py_gom\test1.py 이렇게 입력하였다면 위와 같은 결과를 획득할 수 있다.