본문 바로가기
Python

[Python] sys 모듈

by ds31x 2023. 9. 25.

sys 모듈은

  • interpreter에 의해 사용되거나 유지되는 variables와
  • interpreter와 밀접(interpreter 종료 등)하게 관련된 functions에

대한 access를 제공함.

Python VM (or Interpreter)와의 상호작용 담당.

주로 많이 이용되는 attributes는 다음과 같음.


sys.argv

Python script에 command line을 통해 전달된 argument list.

  • argv[0] : script file 이름.
  • argv[1] 부터는 script file 명 다음에 전달된 argument임. 공백문자로 구분됨.

python -c 를 통해 python code가 주어진 경우에는 argv[0]-c임.

 

참고로 Unix의 경우, OS로부터 넘겨지는 command line arguements는 bytes임.

Python이 이를 file system의 encoding으로 decode하여 sys.argv가 되기 때문에 원래의 bytes로 얻기위해선 [os.fsencode(arg) for arg in sys.argv]와 같이 다시 file system의 encoding으로 encode가 필요함.

https://dsaint31.tistory.com/477

 

[Python] argparse 사용하기.

Python에서 기본적으로 제공하는 명령어 인자 파서 모듈이다. command line 으로 프로그램을 만들 때 기본적으로 필요하다. linux 쪽 경험이 풍부한 이들에겐 getopt가 보다 익숙하지만 그런 사람이면,

dsaint31.tistory.com


sys.executable

현재 수행되는 python interpreter의 executable binary의 absolute path를 나타내는 문자열.

(쉽게 말하면, python 명령의 절대 경로 임.)

 

해당 경로가 검색가능하지 않으면 None 혹은 empty string을 가짐.

https://dsaint31.tistory.com/330

 

[Python] 현재 사용 중인 Python 및 패키지의 실제 경로 확인하기.

LINUX which python 실행되는 Python의 경로를 보여줌. Python shell (패키지 및 python library위치) # 사용중인 python 경로 import sys print(sys.executable) # python library from distutils.sysconfig import get_python_lib print(get_python_

dsaint31.tistory.com

 


sys.exit([arg])

Python interpreter에게 종료를 지시한다.

(Python interactive shell에서는 exit()를 이용)

 

주로 script에서 프로그램의 종료를 지시하기 위해 사용된다.

  • arg는 일반적으로 문제 없이 종료했음을 나타내는 0임.
  • 다른 int 값인 경우엔 OS 에게 Python interpreter가 비정상종료임을 알려줌.
    • Python interpreter종료 직후 echo $? 를 수행해서 확인 가능.
  • 단, 위와 같이 OS에게 알려주는 값은 시스템 레벨로 전달되는 것이라 tryexcept로 확인할 수 없음.

exit()와 마찬가지로 SystemExit exception을 발생시키는 건 같지만,

exit()site-packages에 기반하는 것과 달리

이는 sys 모듈에 있기 때문에 import sys를 먼저 실행해야 한다.

 

주로 script나 python code에서 프로그램 종료를 위해 사용된다.

python -S로 python interactive shell을 수행할 경우,
site-packages가 로드되지 않기 때문(-S 의 동작특성)에
exit를 호출시 Not Defined NameError가 뜬다.

하지만 sys.exit는 명시적으로
import sys를 하기때문에 해당 문제가 발생하지 않음.

 

 

넘겨지는 argument 에 대해선 다음을 참고하라.

https://ds31x.tistory.com/342

 

[Py] sys.exit()

Python의 sys.exit() 는 소스코드 내에서 프로그램을 종료(=pvm종료)시키기 위해 호출하는 함수임.호출(call)할 때, 종료 상태 코드를 argument로 전달받음.해당 종료상태코드는 sys모듈을 통해 os로 넘어감

ds31x.tistory.com


sys.path

Python의 패키지 및 모듈의 경로들을 문자열로 가지고 있는 list.

  • Python interpreter가 패키지나 모듈을 찾기 위한 참조 경로를 item으로 가짐.

아래의 sys.module과 함께 module search path를 관리하는 중요한 attributes임.


sys.module

Python interpreter가 현재 로딩한 모듈과 package를 저장하고 있는 dictionary.

 

1. import 문을 만나면 이 곳에 있는지를 확인하고

2. 없는 경우 builtinssys.path에서 대상 모듈을 찾아 로딩하고 

3. 이를 sys.module에 추가함.

 

모듈과 관련된 자세한 내용은 이 링크를 참고: https://dsaint31.tistory.com/528

 

[Python] Module Search Path and sys.path

1. Module Search Path Python 에서 module을 찾는 경로 (Module Search Path)는 다음의 순서별로 우선권을 가짐. home directory of the program (main script file이 있는 위치 or python shell이 수행된 cwd) PYTHONPATH 환경변수 (envi

dsaint31.tistory.com


References

https://docs.python.org/3/library/sys.html

 

sys — System-specific parameters and functions

This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available. Citations C99, ISO/IEC 9899...

docs.python.org

 

https://ds31x.tistory.com/page/Python-Python-%EC%A0%95%EB%A6%AC

 

[Python] Python 정리

Programming Language and Python 소개2023.10.23 - [Python] - [Python] Programming Language and Introduction of Python. [Python] Programming Language and Introduction of Python.Computer and Program https://dsaint31.tistory.com/436 [CE] Computer and Progra

ds31x.tistory.com

 

728x90