00 개요
- 회사에서 코드분석 하는데 os가 뭘 하는지 알아보기 위한 정리
01 os 모듈이란
1. os 모듈 정의
- 운영 체제 종속 기능들을 사용할 수 있도록 하는 모듈
2. os 모듈의 기능
- 파일 읽고 쓰기 (os.open()), 경로 조작 (os.path()), 환경 변수 갖고오기 (os.environ) 등
02 os 사용
0. os 모듈 참조
- os 는 파이썬 내장 모듈이라서 설치 불필요
import os
1. 프로세스 파라미터
- 현재 프로세스와 사용자에 관한 정보 제공 및 현재 프로세스와 사용자로서 실행
1) os.ctermid()
반환값: 프로세스의 controlling 터미널에 동하는 파일이름
2) os.environ
>>> print(os.environ)
{'EGO_CONFDIR': '/sw/LSF/conf/ego/IC_cluster/kernel', 'TERM_PROGRAM_VERSION': '1.85.1', 'LESSOPEN': '||/usr/bin/lesspipe.sh %s', 'LSF_BINDIR': '/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/bin', 'SSH_CLIENT': '10.0.0.30 63183 22', 'SELINUX_USE_CURRENT_RANGE': '', 'LOGNAME': 'root', 'USER': 'root', 'LSF_ENVDIR': '/sw/LSF/conf', 'HOME': '/root', 'PATH': '/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/etc:/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/bin:/root/.vscode-server/bin/0ee08df0cf4527e40edc9aa28f4b5bd38bbff2b2/bin/remote-cli:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin', 'PS1': '\\[\x1b]633;A\x07\\]\\[\x1b]633;A\x07\\][\\u@\\h \\W]\\$ \\[\x1b]633;B\x07\\]\\[\x1b]633;B\x07\\]', 'LD_LIBRARY_PATH': '/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/lib', 'TERM_PROGRAM': 'vscode', 'LANG': 'en_US.UTF-8', 'LSF_SERVERDIR': '/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/etc', 'TERM': 'xterm-256color', 'SHELL': '/bin/bash', 'EGO_BINDIR': '/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/bin', 'SHLVL': '5', 'EGO_ESRVDIR': '/sw/LSF/conf/ego/IC_cluster/eservice', 'LSF_LIBDIR': '/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/lib', 'HISTSIZE': '1000', 'VSCODE_IPC_HOOK_CLI': '/run/user/0/vscode-ipc-791b6760-3959-41a6-b5cd-f80ffb7b4681.sock', 'MANPATH': '/sw/LSF/10.1/man:', 'XDG_RUNTIME_DIR': '/run/user/0', 'SELINUX_ROLE_REQUESTED': '', 'EGO_TOP': '/sw/LSF', 'XDG_SESSION_ID': '2371', '_': '/usr/bin/python', 'BROWSER': '/root/.vscode-server/bin/0ee08df0cf4527e40edc9aa28f4b5bd38bbff2b2/bin/helpers/browser.sh', 'EGO_LOCAL_CONFDIR': '/sw/LSF/conf/ego/IC_cluster/kernel', 'SSH_CONNECTION': '10.0.0.30 63183 10.0.0.115 22', 'EGO_SERVERDIR': '/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/etc', 'OLDPWD': '/', 'HOSTNAME': 'dyasiproducer3', 'EGO_LIBDIR': '/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/lib', 'SELINUX_LEVEL_REQUESTED': '', 'HISTCONTROL': 'ignoredups', 'XDG_DATA_DIRS': '/root/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:/usr/local/share:/usr/share', 'PWD': '/data1/scheduler-insight', 'COLORTERM': 'truecolor', 'MAIL': '/var/spool/mail/root', 'LS_COLORS': 'rs=0:di=38;5;27:ln=38;5;51:mh=44;38;5;15:pi=40;38;5;11:so=38;5;13:do=38;5;5:bd=48;5;232;38;5;11:cd=48;5;232;38;5;3:or=48;5;232;38;5;9:mi=05;48;5;232;38;5;15:su=48;5;196;38;5;15:sg=48;5;11;38;5;16:ca=48;5;196;38;5;226:tw=48;5;10;38;5;16:ow=48;5;10;38;5;21:st=48;5;21;38;5;15:ex=38;5;34:*.tar=38;5;9:*.tgz=38;5;9:*.arc=38;5;9:*.arj=38;5;9:*.taz=38;5;9:*.lha=38;5;9:*.lz4=38;5;9:*.lzh=38;5;9:*.lzma=38;5;9:*.tlz=38;5;9:*.txz=38;5;9:*.tzo=38;5;9:*.t7z=38;5;9:*.zip=38;5;9:*.z=38;5;9:*.Z=38;5;9:*.dz=38;5;9:*.gz=38;5;9:*.lrz=38;5;9:*.lz=38;5;9:*.lzo=38;5;9:*.xz=38;5;9:*.bz2=38;5;9:*.bz=38;5;9:*.tbz=38;5;9:*.tbz2=38;5;9:*.tz=38;5;9:*.deb=38;5;9:*.rpm=38;5;9:*.jar=38;5;9:*.war=38;5;9:*.ear=38;5;9:*.sar=38;5;9:*.rar=38;5;9:*.alz=38;5;9:*.ace=38;5;9:*.zoo=38;5;9:*.cpio=38;5;9:*.7z=38;5;9:*.rz=38;5;9:*.cab=38;5;9:*.jpg=38;5;13:*.jpeg=38;5;13:*.gif=38;5;13:*.bmp=38;5;13:*.pbm=38;5;13:*.pgm=38;5;13:*.ppm=38;5;13:*.tga=38;5;13:*.xbm=38;5;13:*.xpm=38;5;13:*.tif=38;5;13:*.tiff=38;5;13:*.png=38;5;13:*.svg=38;5;13:*.svgz=38;5;13:*.mng=38;5;13:*.pcx=38;5;13:*.mov=38;5;13:*.mpg=38;5;13:*.mpeg=38;5;13:*.m2v=38;5;13:*.mkv=38;5;13:*.webm=38;5;13:*.ogm=38;5;13:*.mp4=38;5;13:*.m4v=38;5;13:*.mp4v=38;5;13:*.vob=38;5;13:*.qt=38;5;13:*.nuv=38;5;13:*.wmv=38;5;13:*.asf=38;5;13:*.rm=38;5;13:*.rmvb=38;5;13:*.flc=38;5;13:*.avi=38;5;13:*.fli=38;5;13:*.flv=38;5;13:*.gl=38;5;13:*.dl=38;5;13:*.xcf=38;5;13:*.xwd=38;5;13:*.yuv=38;5;13:*.cgm=38;5;13:*.emf=38;5;13:*.axv=38;5;13:*.anx=38;5;13:*.ogv=38;5;13:*.ogx=38;5;13:*.aac=38;5;45:*.au=38;5;45:*.flac=38;5;45:*.mid=38;5;45:*.midi=38;5;45:*.mka=38;5;45:*.mp3=38;5;45:*.mpc=38;5;45:*.ogg=38;5;45:*.ra=38;5;45:*.wav=38;5;45:*.axa=38;5;45:*.oga=38;5;45:*.spx=38;5;45:*.xspf=38;5;45:', 'BINARY_TYPE_HPC': ''}
>>> print(type(os.environ))
<type 'instance'>
- 반환값: 프로세스 환경변수 (process environment)를 나타내는 string 형태로된 key와 values 값들로 이루어진 매핑 객체 (mapping object)
- this mapping may be used to modify the environment or query the environment
3) os.uname()
>>> print(os.uname())
('Linux', 'dyasiproducer3', '3.10.0-957.el7.x86_64', '#1 SMP Thu Oct 4 20:48:51 UTC 2018', 'x86_64')
>>> print(os.uname()[0])
Linux
- 반환값: tuple 형태, 현재 OS를 식별하는 정보 5가지
- sysname - OS 이름
- nodename - 네트워크 상의 기계 이름 (호스트 이름)
- release - OS 출시 (버전과 비슷)
- version - OS 버전
- machine - 하드웨어 식별자 (플랫폼 이름)
2. 파일 및 디렉토리
1) os.access()
os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)
# scheduler-insight/lsf-python-api/setup.py 예시
if os.access(xlc_path, os.F_OK):
- 실제 UID/GID 사용하여 path에 접근 가능한지 검사하는 함수
- NOTE: most operations will use the effective UID/GID, therefore this routine can be used in a SUID/SGID environment to test if the invoking user has the specified access to path.
- 반환값: True if access is allowed, False if not
- can support specifying paths relative to directory descriptors and not following symlinks
- if effective_ids=True
- access() will perform its access checks using the effective UID/GID instead of the real UID/GID
- may not be supported on some platform
- can check the availability using os.supports_effective_ids (of unavailable, it will raise a NotImplementedError)
- Values to pass as the mode parameter to test the existence, readability, writability and executability of path
- os.F_OK: path의 existence 검사
- os.R_OK: path의 readability 검사
- os.W_OK: path의 writability 검사
- os.X_OK: path가 executability 검사
2) os.getcwd()
- 반환값: string 형태의 current working directory
3) os.listdir()
- 반환값: 리스트 형태의 containing the names of the entries in the directory given by path
os.listdir(path='.')
4) class os.DirEntry
- Object yielded by scandir() to expose the file path and other file attributes of a directory entry
- scandir() will provide as much of this info as possible w/o making additional system calls. When stat() or lstat() call is made, the os.DirEntry object will cache the result
- os.DirEntry instances are not inteded to be stored in long-lived data structure; if you know the file metadata has changed or if a long time has elapsed since calling scandir(), call os.stat(entry.path) to fetch up-to-date information
- b/c the os.DirEntry methods can make OS calls, they may also raise OSError. If you need very fine-grained control over errors, you can catch OSError when calling one of the os.DirEntry methods and handle as appropriate
- to be directly usable as a path-like object, os.DirEntry implements the PathLike interface
- 속성 and 메소드 on a os.DirEntry instance are as follows:
- name
- path
- inode()
- is_dir(*, follow_symlinks=True)
- is_file(*, follow_symlinks=True)
- is_symlink()
- is_junction()
- stat(*, follow_symlinks=True)
- 속성 and 메소드 on a os.DirEntry instance are as follows:
4-1) os.path.abspath()
os.path.abspath(path)
- 반환값: 주어진 path의 절대경로
- On most platforms, equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path))
- 3.6 버전부터는 path-like 객체도 받을 수 있음
3. 프로세스 관리
1) os.popen()
os.popen(cmd, mode='r', buffering=-1)
# 예
if sys.argv[1] == 'bdist_rpm' :
lsidout = os.popen('lsid | head -1').readlines()
lsfversion = lsidout[0].split()[4].split(',')[0]
- Open a pipe to/from command cmd.
- 반환값: an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'
- The returned file object reads or writes text strings rather than bytes
- The buffering argument have the same meaning as the corresponding argument to the built-in open() function
2) os.close()
- 반환값: subprocess가 성공적으로 종료됐을 경우 None, 에러있었을 경우 subprocess의 반환 코드
3) os.system()
os.system(cmd)
- Execute the command (a string) in a subshell.
- This is implemented by calling the Standard C function system(), and has the same limitations.
- Changes to sys.stdin, etc. are not reflected in the environment of the executed command.
- If command generates any output, it will be sent to the interpreter standard output stream.
- The C standard does not specify the meaning of the return value of the C function, so the 반환값 is system-dependent.
- 반환값: 위의 설명 참조
4. 시스템 정보
1) os.pathsep
>>> print(os.environ["PATH"])
/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/etc:/sw/LSF/10.1/linux2.6-glibc2.3-x86_64/bin:/root/.vscode-server/bin/0ee08df0cf4527e40edc9aa28f4b5bd38bbff2b2/bin/remote-cli:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
>>> print(os.pathsep)
:
- the character conventionally used by the OS to separate search path components (as in PATH)
- 예시: ':' for POSIX, ';' for Windows
- Also available via os.path
5. 랜덤 숫자
1) os.getrandom()
os.getrandom(size, flags=0)
- 반환값: Get up to size random bytes, can return less bytes than requested
- These bytes can be used to seed user-space random number generators or for cryptographic purposes.
- relies on entropy gathered from device drivers and other sources of environmental noise.
참조
'Python > 기본문법' 카테고리의 다른 글
@데코레이터 Decorator (파이썬) (0) | 2024.06.28 |
---|---|
_ underscore (파이썬) (0) | 2024.06.28 |
sys (인터프리터 제어 모듈) (0) | 2024.06.13 |
re (정규표현식 작업 모듈) (0) | 2024.06.13 |
파이썬 Type Hint (타입 정보 명시적 표시) (0) | 2024.05.08 |