os — 기타 운영 체제 인터페이스

소스 코드: Lib/os.py


이 모듈은 운영 체제 종속 기능을 사용하는 이식성 있는 방법을 제공합니다. 파일을 읽거나 쓰고 싶으면 open()을 보세요, 경로를 조작하려면 os.path 모듈을 보시고, 명령 줄에서 주어진 모든 파일의 모든 줄을 읽으려면 fileinput 모듈을 보십시오. 임시 파일과 디렉터리를 만들려면 tempfile 모듈을 보시고, 고수준의 파일과 디렉터리 처리는 shutil 모듈을 보십시오.

이러한 기능의 가용성에 대한 참고 사항:

  • 내장된 모든 운영 체제 종속적인 파이썬 모듈의 설계는, 같은 기능을 사용할 수 있는 한, 같은 인터페이스를 사용합니다; 예를 들어, 함수 os.stat(path)path 에 대한 stat 정보를 같은 (POSIX 인터페이스에서 기원한) 형식으로 반환합니다.

  • 특정 운영 체제에 고유한 확장도 os 모듈을 통해서 사용할 수 있지만, 이러한 기능을 사용하는 것은 물론 이식성에 대한 위협입니다.

  • 경로 또는 파일명을 받아들이는 모든 함수는 바이트열과 문자열 객체를 모두 허용하며, 경로나 파일명이 반환되면 같은 형의 객체를 반환합니다.

  • On VxWorks, os.popen, os.fork, os.execv and os.spawn*p* are not supported.

  • On WebAssembly platforms wasm32-emscripten and wasm32-wasi, large parts of the os module are not available or behave differently. API related to processes (e.g. fork(), execve()), signals (e.g. kill(), wait()), and resources (e.g. nice()) are not available. Others like getuid() and getpid() are emulated or stubs.

참고

이 모듈의 모든 함수는, 올바르지 않거나 액세스할 수 없는 파일명과 경로일 때, 또는 올바른 형의 인자이지만, 운영 체제에서 허용하지 않으면 OSError(또는 이것의 서브 클래스)를 발생시킵니다.

exception os.error

내장 OSError 예외의 별칭.

os.name

임포트 된 운영 체제 종속 모듈의 이름. 다음과 같은 이름이 현재 등록되어있습니다: 'posix', 'nt', 'java'.

더 보기

sys.platform has a finer granularity. os.uname() gives system-dependent version information.

platform 모듈은 시스템의 아이덴티티에 대한 자세한 검사를 제공합니다.

파일명, 명령 줄 인자 및 환경 변수

In Python, file names, command line arguments, and environment variables are represented using the string type. On some systems, decoding these strings to and from bytes is necessary before passing them to the operating system. Python uses the filesystem encoding and error handler to perform this conversion (see sys.getfilesystemencoding()).

The filesystem encoding and error handler are configured at Python startup by the PyConfig_Read() function: see filesystem_encoding and filesystem_errors members of PyConfig.

버전 3.1에서 변경: On some systems, conversion using the file system encoding may fail. In this case, Python uses the surrogateescape encoding error handler, which means that undecodable bytes are replaced by a Unicode character U+DCxx on decoding, and these are again translated to the original byte on encoding.

The file system encoding must guarantee to successfully decode all bytes below 128. If the file system encoding fails to provide this guarantee, API functions can raise UnicodeError.

See also the locale encoding.

Python UTF-8 Mode

버전 3.7에 추가: See PEP 540 for more details.

The Python UTF-8 Mode ignores the locale encoding and forces the usage of the UTF-8 encoding:

Note that the standard stream settings in UTF-8 mode can be overridden by PYTHONIOENCODING (just as they can be in the default locale-aware mode).

As a consequence of the changes in those lower level APIs, other higher level APIs also exhibit different default behaviours:

  • Command line arguments, environment variables and filenames are decoded to text using the UTF-8 encoding.

  • os.fsdecode() and os.fsencode() use the UTF-8 encoding.

  • open(), io.open(), and codecs.open() use the UTF-8 encoding by default. However, they still use the strict error handler by default so that attempting to open a binary file in text mode is likely to raise an exception rather than producing nonsense data.

The Python UTF-8 Mode is enabled if the LC_CTYPE locale is C or POSIX at Python startup (see the PyConfig_Read() function).

It can be enabled or disabled using the -X utf8 command line option and the PYTHONUTF8 environment variable.

If the PYTHONUTF8 environment variable is not set at all, then the interpreter defaults to using the current locale settings, unless the current locale is identified as a legacy ASCII-based locale (as described for PYTHONCOERCECLOCALE), and locale coercion is either disabled or fails. In such legacy locales, the interpreter will default to enabling UTF-8 mode unless explicitly instructed not to do so.

The Python UTF-8 Mode can only be enabled at the Python startup. Its value can be read from sys.flags.utf8_mode.

See also the UTF-8 mode on Windows and the filesystem encoding and error handler.

더 보기

PEP 686

Python 3.15 will make Python UTF-8 Mode default.

프로세스 매개 변수

이 함수들과 데이터 항목은 현재 프로세스와 사용자에 관한 정보와 관련 연산을 제공합니다.

os.ctermid()

프로세스의 제어 터미널에 해당하는 파일명을 반환합니다.

Availability: Unix, not Emscripten, not WASI.

os.environ

A mapping object where keys and values are strings that represent the process environment. For example, environ['HOME'] is the pathname of your home directory (on some platforms), and is equivalent to getenv("HOME") in C.

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.

이 매핑은 환경을 조회하는 것뿐 아니라 환경을 수정하는 데도 사용될 수 있습니다. 매핑이 수정될 때 putenv()가 자동으로 호출됩니다.

유닉스에서, 키와 값은 sys.getfilesystemencoding()'surrogateescape' 에러 처리기를 사용합니다. 다른 인코딩을 사용하려면 environb를 사용하십시오.

On Windows, the keys are converted to uppercase. This also applies when getting, setting, or deleting an item. For example, environ['monty'] = 'python' maps the key 'MONTY' to the value 'python'.

참고

Calling putenv() directly does not change os.environ, so it’s better to modify os.environ.

참고

On some platforms, including FreeBSD and macOS, setting environ may cause memory leaks. Refer to the system documentation for putenv().

You can delete items in this mapping to unset environment variables. unsetenv() will be called automatically when an item is deleted from os.environ, and when one of the pop() or clear() methods is called.

버전 3.9에서 변경: PEP 584의 병합(|)과 업데이트(|=) 연산자를 지원하도록 갱신되었습니다.

os.environb

Bytes version of environ: a mapping object where both keys and values are bytes objects representing the process environment. environ and environb are synchronized (modifying environb updates environ, and vice versa).

environb is only available if supports_bytes_environ is True.

버전 3.2에 추가.

버전 3.9에서 변경: PEP 584의 병합(|)과 업데이트(|=) 연산자를 지원하도록 갱신되었습니다.

os.chdir(path)
os.fchdir(fd)
os.getcwd()

이 함수는 파일과 디렉터리에 설명되어 있습니다.

os.fsencode(filename)

Encode path-like filename to the filesystem encoding and error handler; return bytes unchanged.

fsdecode()는 역 함수입니다.

버전 3.2에 추가.

버전 3.6에서 변경: os.PathLike 인터페이스를 구현하는 객체를 받아들이도록 지원이 추가되었습니다.

os.fsdecode(filename)

Decode the path-like filename from the filesystem encoding and error handler; return str unchanged.

fsencode()는 역 함수입니다.

버전 3.2에 추가.

버전 3.6에서 변경: os.PathLike 인터페이스를 구현하는 객체를 받아들이도록 지원이 추가되었습니다.

os.fspath(path)

경로의 파일 시스템 표현을 돌려줍니다.

str이나 bytes가 전달되면, 변경되지 않은 상태로 반환됩니다. 그렇지 않으면 __fspath__()가 호출되고, 해당 값이 str이나 bytes 객체인 한 그 값이 반환됩니다. 다른 모든 경우에는 TypeError가 발생합니다.

버전 3.6에 추가.

class os.PathLike

파일 시스템 경로를 나타내는 객체(예를 들어 pathlib.PurePath)의 추상 베이스 클래스입니다.

버전 3.6에 추가.

abstractmethod __fspath__()

객체의 파일 시스템 경로 표현을 돌려줍니다.

이 메서드는 str이나 bytes 객체만 반환해야 하며, str을 선호합니다.

os.getenv(key, default=None)

Return the value of the environment variable key as a string if it exists, or default if it doesn’t. key is a string. Note that since getenv() uses os.environ, the mapping of getenv() is similarly also captured on import, and the function may not reflect future environment changes.

유닉스에서, 키와 값은 sys.getfilesystemencoding()'surrogateescape' 에러 처리기로 디코딩됩니다. 다른 인코딩을 사용하려면 os.getenvb()를 사용하십시오.

가용성: 유닉스, 윈도우.

os.getenvb(key, default=None)

Return the value of the environment variable key as bytes if it exists, or default if it doesn’t. key must be bytes. Note that since getenvb() uses os.environb, the mapping of getenvb() is similarly also captured on import, and the function may not reflect future environment changes.

getenvb() is only available if supports_bytes_environ is True.

가용성: 유닉스.

버전 3.2에 추가.

os.get_exec_path(env=None)

셸과 비슷하게, 프로세스를 시작할 때 지정된 이름의 실행 파일을 검색할 디렉터리 리스트를 반환합니다. (지정된다면) env 는 PATH를 조회할 환경 변수 딕셔너리 여야 합니다. 기본적으로, envNone이면, environ이 사용됩니다.

버전 3.2에 추가.

os.getegid()

현재 프로세스의 유효(effective) 그룹 ID를 반환합니다. 이것은 현재 프로세스에서 실행 중인 파일의 “set id” 비트에 해당합니다.

Availability: Unix, not Emscripten, not WASI.

os.geteuid()

현재 프로세스의 유효(effective) 사용자 ID를 반환합니다.

Availability: Unix, not Emscripten, not WASI.

os.getgid()

현재 프로세스의 실제(real) 그룹 ID를 반환합니다.

가용성: 유닉스.

The function is a stub on Emscripten and WASI, see WebAssembly platforms for more information.

os.getgrouplist(user, group, /)

Return list of group ids that user belongs to. If group is not in the list, it is included; typically, group is specified as the group ID field from the password record for user, because that group ID will otherwise be potentially omitted.

Availability: Unix, not Emscripten, not WASI.

버전 3.3에 추가.

os.getgroups()

현재 프로세스와 관련된 보충(supplemental) 그룹 ID 목록을 반환합니다.

Availability: Unix, not Emscripten, not WASI.

참고

On macOS, getgroups() behavior differs somewhat from other Unix platforms. If the Python interpreter was built with a deployment target of 10.5 or earlier, getgroups() returns the list of effective group ids associated with the current user process; this list is limited to a system-defined number of entries, typically 16, and may be modified by calls to setgroups() if suitably privileged. If built with a deployment target greater than 10.5, getgroups() returns the current group access list for the user associated with the effective user id of the process; the group access list may change over the lifetime of the process, it is not affected by calls to setgroups(), and its length is not limited to 16. The deployment target value, MACOSX_DEPLOYMENT_TARGET, can be obtained with sysconfig.get_config_var().

os.getlogin()

프로세스의 제어 터미널에 로그인한 사용자의 이름을 반환합니다. 대부분 목적에서, getpass.getuser()를 사용하는 것이 더 유용한데, 이 함수는 환경 변수 LOGNAME 이나 USERNAME을 검사하여 사용자가 누구인지 알아내고, 현재 실제 사용자 ID의 로그인 이름을 얻기 위해 pwd.getpwuid(os.getuid())[0]로 폴백 하기 때문입니다.

Availability: Unix, Windows, not Emscripten, not WASI.

os.getpgid(pid)

프로세스 ID pid 를 갖는 프로세스의 프로세스 그룹 ID를 반환합니다. pid 가 0이면, 현재 프로세스의 프로세스 그룹 id가 반환됩니다.

Availability: Unix, not Emscripten, not WASI.

os.getpgrp()

현재 프로세스 그룹의 ID를 반환합니다.

Availability: Unix, not Emscripten, not WASI.

os.getpid()

현재의 프로세스 ID를 반환합니다.

The function is a stub on Emscripten and WASI, see WebAssembly platforms for more information.

os.getppid()

부모의 프로세스 ID를 반환합니다. 부모 프로세스가 종료했으면, 유닉스에서 반환된 id는 init 프로세스 (1) 중 하나이며, 윈도우에서는 여전히 같은 id인데, 다른 프로세스에서 이미 재사용했을 수 있습니다.

Availability: Unix, Windows, not Emscripten, not WASI.

버전 3.2에서 변경: 윈도우에 대한 지원이 추가되었습니다.

os.getpriority(which, who)

프로그램 스케줄 우선순위를 얻습니다. which 값은 PRIO_PROCESS, PRIO_PGRP 또는 PRIO_USER 중 하나이고, whowhich 에 상대적으로 해석됩니다 (PRIO_PROCESS 면 프로세스 식별자, PRIO_PGRP 면 프로세스 그룹 식별자, PRIO_USER 면 사용자 ID). 0 값의 who는 (각각) 호출하는 프로세스, 호출하는 프로세스의 프로세스 그룹, 호출하는 프로세스의 실제 사용자 ID를 나타냅니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.3에 추가.

os.PRIO_PROCESS
os.PRIO_PGRP
os.PRIO_USER

getpriority()setpriority() 함수의 매개 변숫값

Availability: Unix, not Emscripten, not WASI.

버전 3.3에 추가.

os.PRIO_DARWIN_THREAD
os.PRIO_DARWIN_PROCESS
os.PRIO_DARWIN_BG
os.PRIO_DARWIN_NONUI

getpriority()setpriority() 함수의 매개 변숫값

Availability: macOS

버전 3.12에 추가.

os.getresuid()

현재 프로세스의 실제(real), 유효(effective) 및 저장된(saved) 사용자 ID를 나타내는 튜플 (ruid, euid, suid)를 반환합니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.2에 추가.

os.getresgid()

현재 프로세스의 실제(real), 유효(effective) 및 저장된(saved) 그룹 ID를 나타내는 튜플 (rgid, egid, sgid)를 반환합니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.2에 추가.

os.getuid()

현재 프로세스의 실제(real) 사용자 ID를 반환합니다.

가용성: 유닉스.

The function is a stub on Emscripten and WASI, see WebAssembly platforms for more information.

os.initgroups(username, gid, /)

지정된 사용자 이름이 구성원인 모든 그룹과 지정된 그룹 ID로 구성된 그룹 액세스 목록을 초기화하기 위해 시스템 initgroups()를 호출합니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.2에 추가.

os.putenv(key, value, /)

key 라는 환경 변수를 문자열 value 로 설정합니다. 이러한 환경의 변화는 os.system(), popen() 또는 fork()execv()로 시작된 자식 프로세스에 영향을 줍니다.

Assignments to items in os.environ are automatically translated into corresponding calls to putenv(); however, calls to putenv() don’t update os.environ, so it is actually preferable to assign to items of os.environ. This also applies to getenv() and getenvb(), which respectively use os.environ and os.environb in their implementations.

참고

On some platforms, including FreeBSD and macOS, setting environ may cause memory leaks. Refer to the system documentation for putenv().

key, value를 인자로 감사 이벤트(auditing event) os.putenv를 발생시킵니다.

버전 3.9에서 변경: 이 함수는 이제 항상 사용할 수 있습니다.

os.setegid(egid, /)

현재 프로세스의 유효 그룹 ID를 설정합니다.

Availability: Unix, not Emscripten, not WASI.

os.seteuid(euid, /)

현재 프로세스의 유효 사용자 ID를 설정합니다.

Availability: Unix, not Emscripten, not WASI.

os.setgid(gid, /)

현재 프로세스의 그룹 ID를 설정합니다.

Availability: Unix, not Emscripten, not WASI.

os.setgroups(groups, /)

현재 프로세스와 연관된 보충(supplemental) 그룹 ID의 목록을 groups로 설정합니다. groups 는 시퀀스 여야 하며, 각 요소는 그룹을 식별하는 정수여야 합니다. 이 연산은 대개 슈퍼 유저만 사용할 수 있습니다.

Availability: Unix, not Emscripten, not WASI.

참고

On macOS, the length of groups may not exceed the system-defined maximum number of effective group ids, typically 16. See the documentation for getgroups() for cases where it may not return the same group list set by calling setgroups().

os.setns(fd, nstype=0)

Reassociate the current thread with a Linux namespace. See the setns(2) and namespaces(7) man pages for more details.

If fd refers to a /proc/pid/ns/ link, setns() reassociates the calling thread with the namespace associated with that link, and nstype may be set to one of the CLONE_NEW* constants to impose constraints on the operation (0 means no constraints).

Since Linux 5.8, fd may refer to a PID file descriptor obtained from pidfd_open(). In this case, setns() reassociates the calling thread into one or more of the same namespaces as the thread referred to by fd. This is subject to any constraints imposed by nstype, which is a bit mask combining one or more of the CLONE_NEW* constants, e.g. setns(fd, os.CLONE_NEWUTS | os.CLONE_NEWPID). The caller’s memberships in unspecified namespaces are left unchanged.

fd can be any object with a fileno() method, or a raw file descriptor.

This example reassociates the thread with the init process’s network namespace:

fd = os.open("/proc/1/ns/net", os.O_RDONLY)
os.setns(fd, os.CLONE_NEWNET)
os.close(fd)

Availability: Linux >= 3.0 with glibc >= 2.14.

버전 3.12에 추가.

더 보기

The unshare() function.

os.setpgrp()

Call the system call setpgrp() or setpgrp(0, 0) depending on which version is implemented (if any). See the Unix manual for the semantics.

Availability: Unix, not Emscripten, not WASI.

os.setpgid(pid, pgrp, /)

Call the system call setpgid() to set the process group id of the process with id pid to the process group with id pgrp. See the Unix manual for the semantics.

Availability: Unix, not Emscripten, not WASI.

os.setpriority(which, who, priority)

프로그램 스케줄 우선순위를 설정합니다. which 값은 PRIO_PROCESS, PRIO_PGRP 또는 PRIO_USER 중 하나이고, whowhich 에 상대적으로 해석됩니다 (PRIO_PROCESS 면 프로세스 식별자, PRIO_PGRP 면 프로세스 그룹 식별자, PRIO_USER 면 사용자 ID). 0 값의 who는 (각각) 호출하는 프로세스, 호출하는 프로세스의 프로세스 그룹, 호출하는 프로세스의 실제 사용자 ID를 나타냅니다. priority 는 -20에서 19 사이의 값입니다. 기본 우선순위는 0입니다; 우선순위가 낮으면 더 유리하게 스케줄 됩니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.3에 추가.

os.setregid(rgid, egid, /)

현재 프로세스의 실제(real) 및 유효한(effective) 그룹 ID를 설정합니다.

Availability: Unix, not Emscripten, not WASI.

os.setresgid(rgid, egid, sgid, /)

현재 프로세스의 실제(real), 유효(effective) 및 저장된(saved) 그룹 ID를 설정합니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.2에 추가.

os.setresuid(ruid, euid, suid, /)

현재 프로세스의 실제(real), 유효(effective) 및 저장된(saved) 사용자 ID를 설정합니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.2에 추가.

os.setreuid(ruid, euid, /)

현재 프로세스의 실제(real) 및 유효(effective) 사용자 ID를 설정합니다.

Availability: Unix, not Emscripten, not WASI.

os.getsid(pid, /)

Call the system call getsid(). See the Unix manual for the semantics.

Availability: Unix, not Emscripten, not WASI.

os.setsid()

Call the system call setsid(). See the Unix manual for the semantics.

Availability: Unix, not Emscripten, not WASI.

os.setuid(uid, /)

현재 프로세스의 사용자 ID를 설정합니다.

Availability: Unix, not Emscripten, not WASI.

os.strerror(code, /)

Return the error message corresponding to the error code in code. On platforms where strerror() returns NULL when given an unknown error number, ValueError is raised.

os.supports_bytes_environ

환경의 원시 OS 형이 바이트열이면 True (예를 들어, 윈도우에서는 False).

버전 3.2에 추가.

os.umask(mask, /)

현재 숫자 umask를 설정하고 이전 umask를 반환합니다.

The function is a stub on Emscripten and WASI, see WebAssembly platforms for more information.

os.uname()

현재 운영 체제를 식별하는 정보를 반환합니다. 반환 값은 5가지 어트리뷰트를 가진 객체입니다:

  • sysname - 운영 체제 이름

  • nodename - 네트워크상의 기계 이름 (구현이 정의)

  • release - 운영 체제 릴리스

  • version - 운영 체제 버전

  • machine - 하드웨어 식별자

하위 호환성을 위해, 이 객체는 이터러블이기도 해서, sysname, nodename, release, versionmachine이 이 순서로 포함된 5-튜플처럼 작동합니다.

일부 시스템에서는 nodename을 8자나 선행 구성 요소로 자릅니다; 호스트 이름을 얻는 더 좋은 방법은 socket.gethostname() 또는 더 나아가 socket.gethostbyaddr(socket.gethostname())입니다.

가용성: 유닉스.

버전 3.3에서 변경: 반환형이 튜플에서 이름이 지정된 어트리뷰트를 가진 튜플류 객체로 변경되었습니다.

os.unsetenv(key, /)

key 라는 이름의 환경 변수를 삭제합니다. 이러한 환경 변화는 os.system(), popen() 또는 fork()execv()로 시작된 자식 프로세스에 영향을 줍니다.

Deletion of items in os.environ is automatically translated into a corresponding call to unsetenv(); however, calls to unsetenv() don’t update os.environ, so it is actually preferable to delete items of os.environ.

key를 인자로 감사 이벤트(auditing event) os.unsetenv를 발생시킵니다.

버전 3.9에서 변경: 이 함수는 이제 항상 사용할 수 있고 윈도우에서도 사용할 수 있습니다.

os.unshare(flags)

Disassociate parts of the process execution context, and move them into a newly created namespace. See the unshare(2) man page for more details. The flags argument is a bit mask, combining zero or more of the CLONE_* constants, that specifies which parts of the execution context should be unshared from their existing associations and moved to a new namespace. If the flags argument is 0, no changes are made to the calling process’s execution context.

Availability: Linux >= 2.6.16.

버전 3.12에 추가.

더 보기

The setns() function.

Flags to the unshare() function, if the implementation supports them. See unshare(2) in the Linux manual for their exact effect and availability.

os.CLONE_FILES
os.CLONE_FS
os.CLONE_NEWCGROUP
os.CLONE_NEWIPC
os.CLONE_NEWNET
os.CLONE_NEWNS
os.CLONE_NEWPID
os.CLONE_NEWTIME
os.CLONE_NEWUSER
os.CLONE_NEWUTS
os.CLONE_SIGHAND
os.CLONE_SYSVSEM
os.CLONE_THREAD
os.CLONE_VM

파일 객체 생성

이 함수들은 새로운 파일 객체를 만듭니다. (파일 기술자를 여는 것에 관해서는 open()를 참조하십시오.)

os.fdopen(fd, *args, **kwargs)

파일 기술자 fd에 연결된 열린 파일 객체를 반환합니다. 이것은 open() 내장 함수의 별칭이며 같은 인자를 받아들입니다. 유일한 차이점은 fdopen()의 첫 번째 인자는 항상 정수여야 한다는 것입니다.

파일 기술자 연산

이 함수들은 파일 기술자를 사용하여 참조된 I/O 스트림에 작용합니다.

파일 기술자는 현재 프로세스에 의해 열린 파일에 대응하는 작은 정수입니다. 예를 들어, 표준 입력은 보통 파일 기술자 0이고, 표준 출력은 1이며, 표준 에러는 2입니다. 프로세스에 의해 열린 추가 파일은 3, 4, 5 등으로 지정됩니다. “파일 기술자”라는 이름은 약간 기만적입니다; 유닉스 플랫폼에서, 소켓과 파이프도 파일 기술자에 의해 참조됩니다.

fileno() 메서드는 필요할 때 파일 객체와 연관된 파일 기술자를 얻는 데 사용될 수 있습니다. 파일 기술자를 직접 사용하면 파일 객체 메서드를 거치지 않아서, 데이터의 내부 버퍼링과 같은 측면을 무시하게 되는 것에 유의하십시오.

os.close(fd)

파일 기술자 fd를 닫습니다.

참고

이 함수는 저수준 I/O를 위한 것이며, os.open() 또는 pipe()에 의해 반환된 파일 기술자에 적용되어야 합니다. 내장 함수 open()popen() 또는 fdopen()에 의해 반환된 “파일 객체”를 닫으려면, close() 메서드를 사용하십시오.

os.closerange(fd_low, fd_high, /)

에러는 무시하면서, fd_low(포함)부터 fd_high(제외)까지 모든 파일 기술자를 닫습니다. 다음과 동등합니다 (하지만 훨씬 빠릅니다):

for fd in range(fd_low, fd_high):
    try:
        os.close(fd)
    except OSError:
        pass
os.copy_file_range(src, dst, count, offset_src=None, offset_dst=None)

Copy count bytes from file descriptor src, starting from offset offset_src, to file descriptor dst, starting from offset offset_dst. If offset_src is None, then src is read from the current position; respectively for offset_dst.

In Linux kernel older than 5.3, the files pointed by src and dst must reside in the same filesystem, otherwise an OSError is raised with errno set to errno.EXDEV.

This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel. Additionally, some filesystems could implement extra optimizations, such as the use of reflinks (i.e., two or more inodes that share pointers to the same copy-on-write disk blocks; supported file systems include btrfs and XFS) and server-side copy (in the case of NFS).

The function copies bytes between two file descriptors. Text options, like the encoding and the line ending, are ignored.

반환 값은 복사된 바이트의 양입니다. 이것은 요구된 양보다 적을 수 있습니다.

참고

On Linux, os.copy_file_range() should not be used for copying a range of a pseudo file from a special filesystem like procfs and sysfs. It will always copy no bytes and return 0 as if the file was empty because of a known Linux kernel issue.

Availability: Linux >= 4.5 with glibc >= 2.27.

버전 3.8에 추가.

os.device_encoding(fd)

fd 와 연관된 장치가 터미널에 연결되어 있을 때 인코딩을 설명하는 문자열을 반환합니다; 그렇지 않으면 None을 반환합니다.

On Unix, if the Python UTF-8 Mode is enabled, return 'UTF-8' rather than the device encoding.

버전 3.10에서 변경: On Unix, the function now implements the Python UTF-8 Mode.

os.dup(fd, /)

파일 기술자 fd 의 복사본을 반환합니다. 새 파일 기술자는 상속 불가능합니다.

윈도우에서는, 표준 스트림(0: stdin, 1: stdout, 2: stderr)을 복제할 때, 새 파일 기술자가 상속 가능합니다.

Availability: not WASI.

버전 3.4에서 변경: 새로운 파일 기술자는 이제 상속 불가능합니다.

os.dup2(fd, fd2, inheritable=True)

파일 기술자 fdfd2에 복제하고, 필요하면 먼저 후자를 닫습니다. fd2를 반환합니다. 새로운 파일 기술자는 기본적으로 상속 가능하고, inheritableFalse면 상속 불가능합니다.

Availability: not WASI.

버전 3.4에서 변경: 선택적 inheritable 매개 변수를 추가했습니다.

버전 3.7에서 변경: 성공하면 fd2 를 반환합니다. 이전에는 항상 None을 반환했습니다.

os.fchmod(fd, mode)

fd 에 의해 주어진 파일의 모드를 숫자 mode 로 변경합니다. mode의 가능한 값은 chmod() 문서를 참조하십시오. 파이썬 3.3부터는, os.chmod(fd, mode)와 같습니다.

path, mode, dir_fd를 인자로 감사 이벤트(auditing event) os.chmod를 발생시킵니다.

가용성: 유닉스.

The function is limited on Emscripten and WASI, see WebAssembly platforms for more information.

os.fchown(fd, uid, gid)

fd 에 의해 주어진 파일의 소유자와 그룹 id를 숫자 uidgid로 변경합니다. ID 중 하나를 변경하지 않으려면, 그것을 -1로 설정하십시오. chown()를 참조하십시오. 파이썬 3.3부터는, os.chown(fd, uid, gid)와 같습니다.

path, uid, gid, dir_fd를 인자로 감사 이벤트(auditing event) os.chown을 발생시킵니다.

가용성: 유닉스.

The function is limited on Emscripten and WASI, see WebAssembly platforms for more information.

os.fdatasync(fd)

파일 기술자 fd 로 주어진 파일을 디스크에 쓰도록 강제합니다. 메타 데이터를 갱신하도록 강제하지 않습니다.

가용성: 유닉스.

참고

이 함수는 MacOS에서는 사용할 수 없습니다.

os.fpathconf(fd, name, /)

열린 파일과 관련된 시스템 구성 정보를 반환합니다. name 은 조회할 구성 값을 지정합니다; 정의된 시스템 값의 이름인 문자열일 수 있습니다; 이 이름은 여러 표준(POSIX.1, 유닉스 95, 유닉스 98 및 기타)에서 지정됩니다. 일부 플랫폼은 추가 이름도 정의합니다. 호스트 운영 체제에 알려진 이름은 pathconf_names 딕셔너리에서 제공됩니다. 이 매핑에 포함되지 않은 구성 변수의 경우, name에 정수를 전달하는 것도 허용됩니다.

name 이 문자열이고 알 수 없으면, ValueError가 발생합니다. name에 대한 특정 값이 호스트 시스템에서 지원되지 않으면, pathconf_names에 포함되어 있어도, 에러 번호가 errno.EINVALOSError가 발생합니다.

파이썬 3.3부터, os.pathconf(fd, name)과 같습니다.

가용성: 유닉스.

os.fstat(fd)

파일 기술자 fd 의 상태를 가져옵니다. stat_result 객체를 반환합니다.

파이썬 3.3부터는, os.stat(fd)와 같습니다.

더 보기

stat() 함수.

os.fstatvfs(fd, /)

statvfs() 처럼, 파일 기술자 fd 와 연관된 파일을 포함하는 파일 시스템에 대한 정보를 반환합니다. 파이썬 3.3부터는, os.statvfs(fd)와 같습니다.

가용성: 유닉스.

os.fsync(fd)

Force write of file with filedescriptor fd to disk. On Unix, this calls the native fsync() function; on Windows, the MS _commit() function.

버퍼링 된 파이썬 파일 객체 f로 시작하는 경우, f 와 연관된 모든 내부 버퍼가 디스크에 기록되게 하려면, 먼저 f.flush()를 수행한 다음 os.fsync(f.fileno())를 하십시오.

가용성: 유닉스, 윈도우.

os.ftruncate(fd, length, /)

파일 기술자 fd에 해당하는 파일을 잘라내어 최대 length 바이트가 되도록 만듭니다. 파이썬 3.3부터는, os.truncate(fd, length)와 같습니다.

fd, length를 인자로 감사 이벤트(auditing event) os.truncate를 발생시킵니다.

가용성: 유닉스, 윈도우.

버전 3.5에서 변경: 윈도우 지원 추가

os.get_blocking(fd, /)

파일 기술자의 블로킹 모드를 얻어옵니다: O_NONBLOCK 플래그가 설정되었으면 False, 플래그가 지워졌으면 True.

set_blocking()socket.socket.setblocking()도 참조하십시오.

가용성: 유닉스, 윈도우.

The function is limited on Emscripten and WASI, see WebAssembly platforms for more information.

On Windows, this function is limited to pipes.

버전 3.5에 추가.

버전 3.12에서 변경: Added support for pipes on Windows.

os.isatty(fd, /)

파일 기술자 fd 가 열려 있고 tty(류의) 장치에 연결되어 있으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

os.lockf(fd, cmd, len, /)

열린 파일 기술자에 POSIX 록을 적용, 검사 또는 제거합니다. fd 는 열린 파일 기술자입니다. cmd 는 사용할 명령을 지정합니다 - F_LOCK, F_TLOCK, F_ULOCK 또는 F_TEST 중 하나. len 은 잠글 파일의 영역을 지정합니다.

fd, cmd, len을 인자로 감사 이벤트(auditing event) os.lockf를 발생시킵니다.

가용성: 유닉스.

버전 3.3에 추가.

os.F_LOCK
os.F_TLOCK
os.F_ULOCK
os.F_TEST

lockf()가 취할 조치를 지정하는 플래그.

가용성: 유닉스.

버전 3.3에 추가.

os.login_tty(fd, /)

Prepare the tty of which fd is a file descriptor for a new login session. Make the calling process a session leader; make the tty the controlling tty, the stdin, the stdout, and the stderr of the calling process; close fd.

Availability: Unix, not Emscripten, not WASI.

버전 3.11에 추가.

os.lseek(fd, pos, whence, /)

Set the current position of file descriptor fd to position pos, modified by whence, and return the new position in bytes relative to the start of the file. Valid values for whence are:

  • SEEK_SET or 0 – set pos relative to the beginning of the file

  • SEEK_CUR or 1 – set pos relative to the current file position

  • SEEK_END or 2 – set pos relative to the end of the file

  • SEEK_HOLE – set pos to the next data location, relative to pos

  • SEEK_DATA – set pos to the next data hole, relative to pos

버전 3.3에서 변경: Add support for SEEK_HOLE and SEEK_DATA.

os.SEEK_SET
os.SEEK_CUR
os.SEEK_END

Parameters to the lseek() function and the seek() method on file-like objects, for whence to adjust the file position indicator.

SEEK_SET

Adjust the file position relative to the beginning of the file.

SEEK_CUR

Adjust the file position relative to the current file position.

SEEK_END

Adjust the file position relative to the end of the file.

Their values are 0, 1, and 2, respectively.

os.SEEK_HOLE
os.SEEK_DATA

Parameters to the lseek() function and the seek() method on file-like objects, for seeking file data and holes on sparsely allocated files.

SEEK_DATA

Adjust the file offset to the next location containing data, relative to the seek position.

SEEK_HOLE

Adjust the file offset to the next location containing a hole, relative to the seek position. A hole is defined as a sequence of zeros.

참고

These operations only make sense for filesystems that support them.

Availability: Linux >= 3.1, macOS, Unix

버전 3.3에 추가.

os.open(path, flags, mode=0o777, *, dir_fd=None)

파일 path를 열고 flags 에 따른 다양한 플래그와 때로 mode 따른 모드를 설정합니다. mode를 계산할 때, 현재 umask 값으로 먼저 마스킹합니다. 새롭게 열린 파일의 파일 기술자를 돌려줍니다. 새 파일 기술자는 상속 불가능합니다.

플래그와 모드 값에 대한 설명은, C 런타임 설명서를 참조하십시오; 플래그 상수(O_RDONLYO_WRONLY와 같은)는 os 모듈에 정의되어 있습니다. 특히, 윈도우에서 바이너리 모드로 파일을 열려면 O_BINARY를 추가해야 합니다.

이 함수는 dir_fd 매개 변수로 디렉터리 기술자에 상대적인 경로를 지원할 수 있습니다.

path, mode, flags를 인자로 감사 이벤트(auditing event) open을 발생시킵니다.

버전 3.4에서 변경: 새로운 파일 기술자는 이제 상속 불가능합니다.

참고

이 함수는 저수준 I/O를 위한 것입니다. 일반적인 사용을 위해서는 내장 함수 open()을 사용하십시오, 이 함수는 read()write() 메서드(와 더 많은 메서드)가있는 파일 객체를 반환합니다. 파일 기술자를 파일 객체로 싸려면, fdopen()을 사용하십시오.

버전 3.3에서 변경: dir_fd 매개 변수가 추가되었습니다.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 함수는 이제 InterruptedError 예외를 일으키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475를 참조하세요).

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

다음 상수는 open() 함수에 대한 flags 매개 변수의 옵션입니다. 비트별 OR 연산자 |를 사용하여 결합할 수 있습니다. 일부는 모든 플랫폼에서 사용할 수는 없습니다. 가용성과 사용에 대한 설명은 유닉스의 open(2) 매뉴얼 페이지 또는 윈도우의 MSDN을 참조하십시오.

os.O_RDONLY
os.O_WRONLY
os.O_RDWR
os.O_APPEND
os.O_CREAT
os.O_EXCL
os.O_TRUNC

위의 상수는 유닉스 및 윈도우에서 사용할 수 있습니다.

os.O_DSYNC
os.O_RSYNC
os.O_SYNC
os.O_NDELAY
os.O_NONBLOCK
os.O_NOCTTY
os.O_CLOEXEC

위의 상수는 유닉스에서만 사용할 수 있습니다.

버전 3.3에서 변경: O_CLOEXEC 상수를 추가합니다.

os.O_BINARY
os.O_NOINHERIT
os.O_SHORT_LIVED
os.O_TEMPORARY
os.O_RANDOM
os.O_SEQUENTIAL
os.O_TEXT

위의 상수는 윈도우에서만 사용할 수 있습니다.

os.O_EVTONLY
os.O_FSYNC
os.O_NOFOLLOW_ANY

The above constants are only available on macOS.

버전 3.10에서 변경: Add O_EVTONLY, O_FSYNC, O_SYMLINK and O_NOFOLLOW_ANY constants.

os.O_ASYNC
os.O_DIRECT
os.O_DIRECTORY
os.O_NOFOLLOW
os.O_NOATIME
os.O_PATH
os.O_TMPFILE
os.O_SHLOCK
os.O_EXLOCK

위의 상수는 확장이며 C 라이브러리에서 정의하지 않으면 존재하지 않습니다.

버전 3.4에서 변경: 지원하는 시스템에 O_PATH를 추가합니다. 리눅스 커널 3.11 이상에서만 사용 가능한 O_TMPFILE를 추가합니다.

os.openpty()

새로운 의사 터미널 쌍을 엽니다. 파일 기술자의 쌍 (master, slave) 를 반환하는데, 각각 pty와 tty 입니다. 새 파일 기술자는 상속 불가능합니다. (약간) 더 이식성 있는 접근 방식을 사용하려면, pty 모듈을 사용하십시오.

Availability: Unix, not Emscripten, not WASI.

버전 3.4에서 변경: 새로운 파일 기술자는 이제 상속 불가능합니다.

os.pipe()

파이프를 만듭니다. 파일 기술자 쌍 (r, w) 를 반환하는데, 각각 읽기와 쓰기에 사용할 수 있습니다. 새 파일 기술자는 상속 불가능합니다.

가용성: 유닉스, 윈도우.

버전 3.4에서 변경: 새로운 파일 기술자는 이제 상속 불가능합니다.

os.pipe2(flags, /)

flags 가 원자적으로 설정된 파이프를 만듭니다. flags 는 다음과 같은 값들을 하나 이상 OR 해서 만들 수 있습니다: O_NONBLOCK, O_CLOEXEC. 파일 기술자 쌍 (r, w) 를 반환하는데, 각각 읽기와 쓰기에 사용할 수 있습니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.3에 추가.

os.posix_fallocate(fd, offset, len, /)

fd로 지정된 파일이 offset 에서 시작하여 len 바이트 동안 계속되도록 충분한 디스크 공간을 할당합니다.

Availability: Unix, not Emscripten.

버전 3.3에 추가.

os.posix_fadvise(fd, offset, len, advice, /)

특정 패턴으로 데이터에 액세스하려는 의도를 알려 커널이 최적화할 수 있도록 합니다. 조언(advice)은 fd에 의해 지정된 파일의 offset 에서 시작하여 len 바이트 동안 계속되는 영역에 적용됩니다. advicePOSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL, POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED 또는 POSIX_FADV_DONTNEED 중 하나입니다.

가용성: 유닉스.

버전 3.3에 추가.

os.POSIX_FADV_NORMAL
os.POSIX_FADV_SEQUENTIAL
os.POSIX_FADV_RANDOM
os.POSIX_FADV_NOREUSE
os.POSIX_FADV_WILLNEED
os.POSIX_FADV_DONTNEED

사용 가능성이 큰 액세스 패턴을 지정하는 posix_fadvise()advice 에 사용될 수 있는 플래그.

가용성: 유닉스.

버전 3.3에 추가.

os.pread(fd, n, offset, /)

파일 기술자 fd에서 offset 의 위치부터 최대 n 바이트를 읽어 들이고, 파일 오프셋은 변경되지 않은 채로 남겨 둡니다.

읽어 들인 바이트를 포함하는 바이트열을 돌려줍니다. fd 에 의해 참조된 파일의 끝에 도달하면, 빈 바이트열 객체가 반환됩니다.

가용성: 유닉스.

버전 3.3에 추가.

os.preadv(fd, buffers, offset, flags=0, /)

파일 기술자 fd에서 offset 위치부터 가변 바이트열류 객체들 buffers 로 읽어 들이고, 파일 오프셋은 변경되지 않은 채로 남겨 둡니다. 데이터가 가득 찰 때까지 각 버퍼로 데이터를 전송한 다음 나머지 데이터를 보관하기 위해 시퀀스의 다음 버퍼로 이동합니다.

flags 인자는 다음 플래그 중 0개 이상의 비트별 OR를 포함합니다:

실제로 읽힌 총 바이트 수를 반환합니다. 이 값은 모든 객체의 총 용량보다 작을 수 있습니다.

운영 체제는 사용할 수 있는 버퍼 수에 한계(sysconf()'SC_IOV_MAX')를 설정할 수 있습니다.

os.readv()os.pread()의 기능을 결합합니다.

Availability: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.

Using flags requires Linux >= 4.6.

버전 3.7에 추가.

os.RWF_NOWAIT

즉시 사용할 수 없는 데이터를 기다리지 않습니다. 이 플래그를 지정하면, 하부 저장 장치에서 데이터를 읽어야 하거나 록을 기다려야 할 때 즉시 시스템 호출이 반환됩니다.

If some data was successfully read, it will return the number of bytes read. If no bytes were read, it will return -1 and set errno to errno.EAGAIN.

Availability: Linux >= 4.14.

버전 3.7에 추가.

os.RWF_HIPRI

우선순위가 높은 읽기/쓰기. 블록 기반 파일 시스템이 장치의 폴링을 사용할 수 있게 하여, 지연은 짧아 지지만, 추가 자원을 사용할 수 있습니다.

현재, 리눅스에서, 이 기능은 O_DIRECT 플래그를 사용하여 열린 파일 기술자에만 사용할 수 있습니다.

Availability: Linux >= 4.6.

버전 3.7에 추가.

os.pwrite(fd, str, offset, /)

파일 기술자 fdoffset 위치에 str 바이트열을 쓰고, 파일 오프셋은 변경되지 않은 채로 남겨 둡니다.

실제로 쓴 바이트 수를 반환합니다.

가용성: 유닉스.

버전 3.3에 추가.

os.pwritev(fd, buffers, offset, flags=0, /)

buffers 내용을 파일 기술자 fd의 오프셋 offset 에 쓰고, 파일 오프셋은 변경되지 않은 채로 남겨 둡니다. buffers바이트열류 객체의 시퀀스 여야 합니다. 버퍼는 배열 순서로 처리됩니다. 첫 번째 버퍼의 전체 내용은 두 번째 버퍼로 진행하기 전에 기록되고, 같은 식으로 계속 진행합니다.

flags 인자는 다음 플래그 중 0개 이상의 비트별 OR를 포함합니다:

실제로 쓴 총 바이트 수를 반환합니다.

운영 체제는 사용할 수 있는 버퍼 수에 한계(sysconf()'SC_IOV_MAX')를 설정할 수 있습니다.

os.writev()os.pwrite()의 기능을 결합합니다.

Availability: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.

Using flags requires Linux >= 4.6.

버전 3.7에 추가.

os.RWF_DSYNC

Provide a per-write equivalent of the O_DSYNC os.open() flag. This flag effect applies only to the data range written by the system call.

Availability: Linux >= 4.7.

버전 3.7에 추가.

os.RWF_SYNC

Provide a per-write equivalent of the O_SYNC os.open() flag. This flag effect applies only to the data range written by the system call.

Availability: Linux >= 4.7.

버전 3.7에 추가.

os.RWF_APPEND

Provide a per-write equivalent of the O_APPEND os.open() flag. This flag is meaningful only for os.pwritev(), and its effect applies only to the data range written by the system call. The offset argument does not affect the write operation; the data is always appended to the end of the file. However, if the offset argument is -1, the current file offset is updated.

Availability: Linux >= 4.16.

버전 3.10에 추가.

os.read(fd, n, /)

파일 기술자 fd에서 최대 n 바이트를 읽습니다.

읽어 들인 바이트를 포함하는 바이트열을 돌려줍니다. fd 에 의해 참조된 파일의 끝에 도달하면, 빈 바이트열 객체가 반환됩니다.

참고

이 함수는 저수준 I/O를 위한 것이며 os.open() 이나 pipe()에 의해 반환된 파일 기술자에 적용되어야 합니다. 내장 함수 open() 이나 popen() 또는 fdopen()에 의해 반환된 “파일 객체”나 sys.stdin을 읽으려면, 그것의 read()readline() 메서드를 사용하십시오.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 함수는 이제 InterruptedError 예외를 일으키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475를 참조하세요).

os.sendfile(out_fd, in_fd, offset, count)
os.sendfile(out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0)

파일 기술자 in_fd에서 파일 기술자 out_fdoffset에서 시작하여 count 바이트를 복사합니다. 전송된 바이트 수를 반환합니다. EOF에 도달하면 0을 반환합니다.

첫 번째 함수 서명은 sendfile()를 정의하는 모든 플랫폼에서 지원됩니다.

리눅스에서, offsetNone으로 주어지면, in_fd의 현재 위치에서 바이트를 읽고 in_fd의 위치가 갱신됩니다.

The second case may be used on macOS and FreeBSD where headers and trailers are arbitrary sequences of buffers that are written before and after the data from in_fd is written. It returns the same as the first case.

On macOS and FreeBSD, a value of 0 for count specifies to send until the end of in_fd is reached.

모든 플랫폼은 out_fd 파일 기술자로 소켓을 지원하고, 일부 플랫폼은 다른 유형(예를 들어 일반 파일, 파이프)들도 허락합니다.

이기종 플랫폼 응용 프로그램은 headers, trailersflags 인자를 사용해서는 안 됩니다.

Availability: Unix, not Emscripten, not WASI.

참고

sendfile()의 고수준 래퍼는, socket.socket.sendfile()을 보십시오.

버전 3.3에 추가.

버전 3.9에서 변경: 매개 변수 outin의 이름이 out_fdin_fd로 변경되었습니다.

os.SF_NODISKIO
os.SF_MNOWAIT
os.SF_SYNC

구현이 지원하는 경우, sendfile() 함수에 대한 매개 변수입니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.3에 추가.

os.SF_NOCACHE

Parameter to the sendfile() function, if the implementation supports it. The data won’t be cached in the virtual memory and will be freed afterwards.

Availability: Unix, not Emscripten, not WASI.

버전 3.11에 추가.

os.set_blocking(fd, blocking, /)

지정된 파일 기술자의 블로킹 모드를 설정합니다. blocking이 FalseO_NONBLOCK 플래그를 설정하고, 그렇지 않으면 플래그를 지웁니다.

get_blocking()socket.socket.setblocking()도 참조하십시오.

가용성: 유닉스, 윈도우.

The function is limited on Emscripten and WASI, see WebAssembly platforms for more information.

On Windows, this function is limited to pipes.

버전 3.5에 추가.

버전 3.12에서 변경: Added support for pipes on Windows.

os.splice(src, dst, count, offset_src=None, offset_dst=None)

Transfer count bytes from file descriptor src, starting from offset offset_src, to file descriptor dst, starting from offset offset_dst. At least one of the file descriptors must refer to a pipe. If offset_src is None, then src is read from the current position; respectively for offset_dst. The offset associated to the file descriptor that refers to a pipe must be None. The files pointed by src and dst must reside in the same filesystem, otherwise an OSError is raised with errno set to errno.EXDEV.

이 복사는 커널에서 사용자 공간으로 데이터를 전송한 다음 다시 커널로 전송하는 추가 비용 없이 수행됩니다. 또한, 일부 파일 시스템은 추가 최적화를 구현할 수 있습니다. 두 파일이 바이너리로 열린 것처럼 복사가 수행됩니다.

Upon successful completion, returns the number of bytes spliced to or from the pipe. A return value of 0 means end of input. If src refers to a pipe, then this means that there was no data to transfer, and it would not make sense to block because there are no writers connected to the write end of the pipe.

Availability: Linux >= 2.6.17 with glibc >= 2.5

버전 3.10에 추가.

os.SPLICE_F_MOVE
os.SPLICE_F_NONBLOCK
os.SPLICE_F_MORE

버전 3.10에 추가.

os.readv(fd, buffers, /)

파일 기술자 fd에서 여러 가변 바이트열류 객체 buffers로 읽어 들입니다. 데이터가 가득 찰 때까지 각 버퍼로 데이터를 전송한 다음 나머지 데이터를 보관하기 위해 시퀀스의 다음 버퍼로 이동합니다.

실제로 읽힌 총 바이트 수를 반환합니다. 이 값은 모든 객체의 총 용량보다 작을 수 있습니다.

운영 체제는 사용할 수 있는 버퍼 수에 한계(sysconf()'SC_IOV_MAX')를 설정할 수 있습니다.

가용성: 유닉스.

버전 3.3에 추가.

os.tcgetpgrp(fd, /)

fd(os.open()에 의해 반환된 것과 같은 열린 파일 기술자)에 의해 주어진 터미널과 관련된 프로세스 그룹을 반환합니다.

Availability: Unix, not WASI.

os.tcsetpgrp(fd, pg, /)

fd(os.open()에 의해 반환된 것과 같은 열린 파일 기술자)에 의해 주어진 터미널과 관련된 프로세스 그룹을 pg로 설정합니다.

Availability: Unix, not WASI.

os.ttyname(fd, /)

파일 기술자 fd와 관련된 터미널 장치를 나타내는 문자열을 돌려줍니다. fd 가 터미널 장치와 연관되어 있지 않으면, 예외가 발생합니다.

가용성: 유닉스.

os.write(fd, str, /)

str 바이트열을 파일 기술자 fd 에 씁니다.

실제로 쓴 바이트 수를 반환합니다.

참고

이 함수는 저수준 I/O를 위한 것이며 os.open() 이나 pipe()에 의해 반환된 파일 기술자에 적용되어야 합니다. 내장 함수 open() 이나 popen() 또는 fdopen()에 의해 반환된 “파일 객체”나 sys.stdout 또는 sys.stderr에 쓰려면, 그것의 write() 메서드를 사용하십시오.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 함수는 이제 InterruptedError 예외를 일으키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475를 참조하세요).

os.writev(fd, buffers, /)

buffers 내용을 파일 기술자 fd에 씁니다. buffers바이트열류 객체의 시퀀스 여야 합니다. 버퍼는 배열 순서로 처리됩니다. 첫 번째 버퍼의 전체 내용은 두 번째 버퍼로 진행하기 전에 기록되고, 같은 식으로 계속 진행합니다.

실제로 쓴 총 바이트 수를 반환합니다.

운영 체제는 사용할 수 있는 버퍼 수에 한계(sysconf()'SC_IOV_MAX')를 설정할 수 있습니다.

가용성: 유닉스.

버전 3.3에 추가.

터미널의 크기 조회하기

버전 3.3에 추가.

os.get_terminal_size(fd=STDOUT_FILENO, /)

터미널 창의 크기를 (columns, lines) 로 반환하는데, terminal_size 형의 튜플입니다.

선택적 인자 fd(기본값 STDOUT_FILENO, 즉 표준 출력)는 조회할 파일 기술자를 지정합니다.

파일 기술자가 터미널에 연결되어 있지 않으면, OSError가 발생합니다.

shutil.get_terminal_size()가 일반적으로 사용해야 하는 고수준 함수이며, os.get_terminal_size는 저수준 구현입니다.

가용성: 유닉스, 윈도우.

class os.terminal_size

터미널 창 크기 (columns, lines)를 저장하는 튜플의 서브 클래스.

columns

문자 단위의 터미널 창의 너비.

lines

문자 단위의 터미널 창의 높이.

파일 기술자의 상속

버전 3.4에 추가.

파일 기술자는 자식 프로세스가 파일 기술자를 상속받을 수 있는지를 나타내는 “상속 가능” 플래그를 가지고 있습니다. 파이썬 3.4부터, 파이썬에 의해 생성된 파일 기술자는 기본적으로 상속 불가능합니다.

유닉스에서는, 상속 불가능한 파일 기술자는 새 프로그램 실행 시 자식 프로세스에서 닫히고, 다른 파일 기술자는 상속됩니다.

윈도우에서는, 항상 상속되는 표준 스트림(파일 기술자 0, 1, 2: stdin, stdout, stderr)을 제외하고, 상속 불가능한 핸들 및 파일 기술자는 자식 프로세스에서 닫힙니다. spawn* 함수를 사용하면, 상속 가능한 모든 핸들과 상속 가능한 모든 파일 기술자가 상속됩니다. subprocess 모듈을 사용하면, 표준 스트림을 제외한 모든 파일 기술자가 닫히고, 상속 가능한 핸들은 close_fds 매개 변수가 False 일 때만 상속됩니다.

On WebAssembly platforms wasm32-emscripten and wasm32-wasi, the file descriptor cannot be modified.

os.get_inheritable(fd, /)

지정된 파일 기술자의 “상속 가능” 플래그를 가져옵니다 (논릿값).

os.set_inheritable(fd, inheritable, /)

지정된 파일 기술자의 “상속 가능(inheritable)” 플래그를 설정합니다.

os.get_handle_inheritable(handle, /)

지정된 핸들의 “상속 가능” 플래그를 가져옵니다 (논릿값).

가용성: 윈도우.

os.set_handle_inheritable(handle, inheritable, /)

지정된 핸들의 “상속 가능(inheritable)” 플래그를 설정합니다.

가용성: 윈도우.

파일과 디렉터리

일부 유닉스 플랫폼에서, 이 함수 중 많은 것들이 다음 기능 중 하나 이상을 지원합니다:

  • 파일 기술자 지정: 일반적으로 os 모듈에 있는 함수에 제공되는 path 인자는 파일 경로를 지정하는 문자열이어야 합니다. 하지만, 일부 함수는 이제 path 인자로 열린 파일 기술자를 대신 받아들입니다. 그러면 그 함수는 기술자가 참조하는 파일에서 작동합니다. (POSIX 시스템에서, 파이썬은 함수의 f 접두어가 붙은 함수의 변종을 호출합니다 (예를 들어, chdir 대신 fchdir).)

    os.supports_fd를 사용하여, 여러분의 플랫폼에서 특정 함수에 파일 기술자로 path를 지정할 수 있는지를 확인할 수 있습니다. 사용할 수 없을 때, 사용하면 NotImplementedError를 발생시킵니다.

    함수가 dir_fdfollow_symlinks 인자도 지원하면, path 에 파일 기술자를 제공할 때, 이 중 하나를 지정하는 것은 에러입니다.

  • 디렉터리 기술자에 상대적인 경로: dir_fdNone이 아니면, 디렉터리를 가리키는 파일 기술자여야 하며, 대상 경로는 상대 경로여야 합니다; 그러면 경로는 그 디렉터리에 상대적입니다. 절대 경로이면, dir_fd 는 무시됩니다. (POSIX 시스템에서, 파이썬은 at 접미사를 붙이거나 어쩌면 f 접두사도 붙인 함수의 변종을 호출합니다. 예를 들어, access 대신 faccessat를 호출합니다)

    os.supports_dir_fd를 사용하여, 여러분의 플랫폼에서 특정 함수에 dir_fd가 지원되는지를 확인할 수 있습니다. 사용할 수 없을 때, 사용하면 NotImplementedError를 발생시킵니다.

os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)

실제(real) uid/gid를 사용해서 path를 액세스할 수 있는지 검사합니다. 대부분의 연산은 유효한(effective) uid/gid를 사용할 것이므로, 이 함수는 suid/sgid 환경에서 호출하는 사용자가 지정된 path 에 대한 액세스 권한이 있는지 검사하는데 사용할 수 있습니다. path가 존재하는지를 검사하려면 modeF_OK 여야 하며, 권한을 검사하려면 하나 이상의 R_OK, W_OKX_OK를 OR 값일 수 있습니다. 액세스가 허용되면 True를 반환하고, 그렇지 않으면 False를 반환합니다. 더 자세한 정보는 유닉스 매뉴얼 페이지 access(2)를 참조하십시오.

이 함수는 디렉터리 기술자에 상대적인 경로심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

effective_idsTrue면, access()는 실제(real) uid/gid 대신 유효한(effective) uid/gid를 사용하여 액세스 검사를 수행합니다. effective_ids 는 플랫폼에서 지원되지 않을 수 있습니다; os.supports_effective_ids를 사용하여, 사용할 수 있는지를 확인할 수 있습니다. 사용할 수 없을 때, 사용하면 NotImplementedError를 발생시킵니다.

참고

예를 들어, 실제로 open()를 사용하여 파일을 열기 전에, access()를 사용하여 파일을 여는 권한이 있는지 확인하는 것은 보안 구멍을 만듭니다. 사용자가 파일을 확인하고 조작을 위해 열기 사이의 짧은 시간 간격을 악용할 수 있기 때문입니다. EAFP 기법을 사용하는 것이 좋습니다. 예를 들면:

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"

는 다음과 같이 쓰는 것이 더 좋습니다:

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()

참고

access()가 성공할 것임을 알릴 때도, I/O 연산이 실패할 수 있습니다. 특히 일반적인 POSIX 권한 비트 모델을 넘어서는 권한 의미가 있을 수 있는 네트워크 파일 시스템에 대한 연산에서 그럴 수 있습니다.

버전 3.3에서 변경: dir_fd, effective_idsfollow_symlinks 매개 변수를 추가했습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.F_OK
os.R_OK
os.W_OK
os.X_OK

path 의 존재 여부, 읽기 가능성, 쓰기 가능성 및 실행 가능성을 검사하기 위해, access()mode 매개 변수로 전달할 값입니다.

os.chdir(path)

현재 작업 디렉터리를 path로 변경합니다.

이 함수는 파일 기술자 지정을 지원할 수 있습니다. 기술자는 열려있는 파일이 아니라, 열려있는 디렉터리를 참조해야 합니다.

이 함수는 OSErrorFileNotFoundError, PermissionErrorNotADirectoryError와 같은 서브 클래스를 발생시킬 수 있습니다.

path를 인자로 감사 이벤트(auditing event) os.chdir을 발생시킵니다.

버전 3.3에서 변경: 일부 플랫폼에서 path 를 파일 기술자로 지정하는 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.chflags(path, flags, *, follow_symlinks=True)

path 의 플래그를 숫자 flags로 설정합니다. flags는 다음 값들(stat 모듈에 정의된 대로)의 조합(비트별 OR)을 취할 수 있습니다:

이 함수는 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

path, flags를 인자로 감사 이벤트(auditing event) os.chflags를 발생시킵니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.3에서 변경: Added the follow_symlinks parameter.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)

path의 모드를 숫자 mode로 변경합니다. mode 는 다음 값들(stat 모듈에 정의된 대로)이나 이들의 비트별 OR 조합을 취할 수 있습니다:

이 함수는 파일 기술자 지정, 디렉터리 기술자에 상대적인 경로심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

참고

윈도우가 chmod()를 지원하더라도, (stat.S_IWRITEstat.S_IREAD 상수나 해당 정숫값을 통해) 파일의 읽기 전용 플래그만 설정할 수 있습니다. 다른 모든 비트는 무시됩니다.

The function is limited on Emscripten and WASI, see WebAssembly platforms for more information.

path, mode, dir_fd를 인자로 감사 이벤트(auditing event) os.chmod를 발생시킵니다.

버전 3.3에서 변경: path를 열린 파일 기술자로 지정하는 지원과 dir_fdfollow_symlinks 인자가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)

path 의 소유자와 그룹 ID를 숫자 uidgid로 변경합니다. ID 중 하나를 변경하지 않으려면, 그것을 -1로 설정하십시오.

이 함수는 파일 기술자 지정, 디렉터리 기술자에 상대적인 경로심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

숫자 ID 이외에 이름을 허용하는 고수준 함수는 shutil.chown()를 참조하십시오.

path, uid, gid, dir_fd를 인자로 감사 이벤트(auditing event) os.chown을 발생시킵니다.

가용성: 유닉스.

The function is limited on Emscripten and WASI, see WebAssembly platforms for more information.

버전 3.3에서 변경: path를 열린 파일 기술자로 지정하는 지원과 dir_fdfollow_symlinks 인자가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 지원합니다.

os.chroot(path)

현재 프로세스의 루트 디렉터리를 path로 변경합니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.fchdir(fd)

현재 작업 디렉터리를 파일 기술자 fd가 나타내는 디렉터리로 변경합니다. 기술자는 열려있는 파일이 아니라 열려있는 디렉터리를 참조해야 합니다. 파이썬 3.3부터는, os.chdir(fd)와 같습니다.

path를 인자로 감사 이벤트(auditing event) os.chdir을 발생시킵니다.

가용성: 유닉스.

os.getcwd()

현재 작업 디렉터리를 나타내는 문자열을 반환합니다.

os.getcwdb()

현재 작업 디렉터리를 나타내는 바이트열을 반환합니다.

버전 3.8에서 변경: 이 함수는 이제 윈도우에서 ANSI 코드 페이지가 아닌 UTF-8 인코딩을 사용합니다: 이유는 PEP 529를 참조하십시오. 이 함수는 윈도우에서 더는 폐지되지 않습니다.

os.lchflags(path, flags)

path 의 플래그를, chflags() 처럼, 숫자 flags로 설정하지만, 심볼릭 링크를 따르지 않습니다. 파이썬 3.3부터는, os.chflags(path, flags, follow_symlinks=False)와 같습니다.

path, flags를 인자로 감사 이벤트(auditing event) os.chflags를 발생시킵니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.lchmod(path, mode)

path 모드를 숫자 mode로 변경합니다. path가 심볼릭 링크면, 이 함수는 타깃이 아닌 심볼릭 링크에 영향을 미칩니다. mode의 가능한 값은 chmod() 문서를 참조하십시오. 파이썬 3.3부터는, os.chmod(path, mode, follow_symlinks=False)와 같습니다.

lchmod() is not part of POSIX, but Unix implementations may have it if changing the mode of symbolic links is supported.

path, mode, dir_fd를 인자로 감사 이벤트(auditing event) os.chmod를 발생시킵니다.

Availability: Unix, not Linux, FreeBSD >= 1.3, NetBSD >= 1.3, not OpenBSD

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.lchown(path, uid, gid)

path 의 소유자와 그룹 ID를 숫자 uidgid로 변경합니다. 이 함수는 심볼릭 링크를 따르지 않습니다. 파이썬 3.3부터는, os.chown(path, uid, gid, follow_symlinks=False)와 같습니다.

path, uid, gid, dir_fd를 인자로 감사 이벤트(auditing event) os.chown을 발생시킵니다.

가용성: 유닉스.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

src를 가리키는 dst 라는 이름의 하드 링크를 만듭니다.

이 함수는 디렉터리 기술자에 상대적인 경로를 제공하기 위해 src_dir_fd 와/나 dst_dir_fd 를 지정하는 것과, 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

src, dst, src_dir_fd, dst_dir_fd를 인자로 감사 이벤트(auditing event) os.link를 발생시킵니다.

Availability: Unix, Windows, not Emscripten.

버전 3.2에서 변경: 윈도우 지원이 추가되었습니다.

버전 3.3에서 변경: Added the src_dir_fd, dst_dir_fd, and follow_symlinks parameters.

버전 3.6에서 변경: srcdst경로류 객체를 받아들입니다.

os.listdir(path='.')

path에 의해 주어진 디렉터리에 있는 항목들의 이름을 담고 있는 리스트를 반환합니다. 리스트는 임의의 순서로 나열되며, 디렉터리에 존재하더라도 특수 항목 '.''..'는 포함하지 않습니다. 이 함수 호출 중에 디렉터리에서 파일이 제거되거나 추가되면, 해당 파일의 이름이 포함되는지는 지정되지 않습니다.

path경로류 객체 일 수 있습니다. pathbytes 형이면 (직접 또는 PathLike 인터페이스를 통해 간접적으로), 반환되는 파일명도 bytes 형입니다; 다른 모든 상황에서는 형 str이 됩니다.

이 함수는 또한 파일 기술자 지정을 지원할 수 있습니다; 파일 기술자는 디렉터리를 참조해야 합니다.

path를 인자로 감사 이벤트(auditing event) os.listdir을 발생시킵니다.

참고

str 파일명을 bytes로 인코딩하려면, fsencode()를 사용하십시오.

더 보기

scandir() 함수는 파일 어트리뷰트 정보와 함께 디렉터리 항목을 반환하므로, 많은 일반적인 사용 사례에서 더 나은 성능을 제공합니다.

버전 3.2에서 변경: path 매개 변수는 선택 사항이 되었습니다.

버전 3.3에서 변경: path에 열린 파일 기술자를 지정하는 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.listdrives()

Return a list containing the names of drives on a Windows system.

A drive name typically looks like 'C:\\'. Not every drive name will be associated with a volume, and some may be inaccessible for a variety of reasons, including permissions, network connectivity or missing media. This function does not test for access.

May raise OSError if an error occurs collecting the drive names.

Raises an auditing event os.listdrives with no arguments.

Availability: Windows

버전 3.12에 추가.

os.listmounts(volume)

Return a list containing the mount points for a volume on a Windows system.

volume must be represented as a GUID path, like those returned by os.listvolumes(). Volumes may be mounted in multiple locations or not at all. In the latter case, the list will be empty. Mount points that are not associated with a volume will not be returned by this function.

The mount points return by this function will be absolute paths, and may be longer than the drive name.

Raises OSError if the volume is not recognized or if an error occurs collecting the paths.

Raises an auditing event os.listmounts with argument volume.

Availability: Windows

버전 3.12에 추가.

os.listvolumes()

Return a list containing the volumes in the system.

Volumes are typically represented as a GUID path that looks like \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\. Files can usually be accessed through a GUID path, permissions allowing. However, users are generally not familiar with them, and so the recommended use of this function is to retrieve mount points using os.listmounts().

May raise OSError if an error occurs collecting the volumes.

Raises an auditing event os.listvolumes with no arguments.

Availability: Windows

버전 3.12에 추가.

os.lstat(path, *, dir_fd=None)

Perform the equivalent of an lstat() system call on the given path. Similar to stat(), but does not follow symbolic links. Return a stat_result object.

심볼릭 링크를 지원하지 않는 플랫폼에서, 이 함수는 stat()의 별칭입니다.

파이썬 3.3부터는, os.stat(path, dir_fd=dir_fd, follow_symlinks=False)와 같습니다.

이 기능은 디렉터리 기술자에 상대적인 경로도 지원할 수 있습니다.

더 보기

stat() 함수.

버전 3.2에서 변경: 윈도우 6.0 (Vista) 심볼릭 링크에 대한 지원이 추가되었습니다.

버전 3.3에서 변경: dir_fd 매개 변수가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.8에서 변경: 윈도우에서, 이제 심볼릭 링크와 디렉터리 정션(directory junction)을 포함하는 다른 경로를 나타내는 재해석 지점(reparse point, 이름 서로게이트)을 엽니다. 다른 유형의 재해석 지점은 운영 체제에서 stat()에서 처럼 결정됩니다.

os.mkdir(path, mode=0o777, *, dir_fd=None)

숫자 모드 modepath 라는 디렉터리를 만듭니다.

If the directory already exists, FileExistsError is raised. If a parent directory in the path does not exist, FileNotFoundError is raised.

일부 시스템에서는, mode가 무시됩니다. 모드가 사용될 때, 현재 umask 값으로 먼저 마스킹합니다. 마지막 9비트 (즉, mode 의 8진 표현의 마지막 3자리 수) 이외의 비트가 설정되면, 그 의미는 플랫폼에 따라 다릅니다. 일부 플랫폼에서는, 이것들이 무시되며, 설정하려면 명시적으로 chmod()를 호출해야 합니다.

이 기능은 디렉터리 기술자에 상대적인 경로도 지원할 수 있습니다.

임시 디렉터리를 만들 수도 있습니다; tempfile 모듈의 tempfile.mkdtemp() 함수를 참조하십시오.

path, mode, dir_fd를 인자로 감사 이벤트(auditing event) os.mkdir을 발생시킵니다.

버전 3.3에서 변경: dir_fd 매개 변수가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.makedirs(name, mode=0o777, exist_ok=False)

재귀적 디렉터리 생성 함수. mkdir()와 비슷하지만, 말단 디렉터리를 포함하는 데 필요한 모든 중간 수준 디렉터리들을 만듭니다.

The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed.

If exist_ok is False (the default), a FileExistsError is raised if the target directory already exists.

참고

makedirs()는 생성할 경로 요소에 pardir(예를 들어, 유닉스 시스템의 경우 “..”)이 포함되어 있으면 혼란해 할 수 있습니다.

이 함수는 UNC 경로를 올바르게 처리합니다.

path, mode, dir_fd를 인자로 감사 이벤트(auditing event) os.mkdir을 발생시킵니다.

버전 3.2에서 변경: Added the exist_ok parameter.

버전 3.4.1에서 변경: 파이썬 3.4.1 이전에는, exist_okTrue이고 디렉터리가 존재한다면, mode 가 기존 디렉터리의 모드와 일치하지 않을 때, makedirs()는 여전히 에러를 발생시킵니다. 이 동작은 안전하게 구현할 수 없으므로, 파이썬 3.4.1에서 제거되었습니다. bpo-21082를 참조하십시오.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.7에서 변경: The mode argument no longer affects the file permission bits of newly created intermediate-level directories.

os.mkfifo(path, mode=0o666, *, dir_fd=None)

숫자 모드 modepath 라는 이름의 FIFO(이름있는 파이프)를 만듭니다. 현재 umask 값으로 먼저 모드를 마스킹합니다.

이 기능은 디렉터리 기술자에 상대적인 경로도 지원할 수 있습니다.

FIFO는 일반 파일처럼 액세스할 수 있는 파이프입니다. FIFO는 삭제될 때까지 존재합니다 (예를 들어 os.unlink()로). 일반적으로, FIFO는 “클라이언트”와 “서버” 유형 프로세스 사이에서 랑데부로 사용됩니다: 서버는 FIFO를 읽기 용도로 열고, 클라이언트는 쓰기 용도로 엽니다. mkfifo()가 FIFO를 열지는 않는다는 점에 유의하십시오 — 단지 랑데부 포인트를 생성합니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.3에서 변경: dir_fd 매개 변수가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.mknod(path, mode=0o600, device=0, *, dir_fd=None)

path 라는 이름의 파일 시스템 노드(파일, 장치 특수 파일 또는 이름있는 파이프)를 만듭니다. mode 는 사용 권한과 생성될 노드의 유형을 모두 지정하며, stat.S_IFREG, stat.S_IFCHR, stat.S_IFBLKstat.S_IFIFO 중 하나와 결합(비트별 OR)합니다 (이 상수들은 stat에 있습니다). stat.S_IFCHRstat.S_IFBLK의 경우, device 는 새로 만들어지는 장치 특수 파일(아마도 os.makedev()를 사용해서)을 정의합니다, 그렇지 않으면 무시됩니다.

이 기능은 디렉터리 기술자에 상대적인 경로도 지원할 수 있습니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.3에서 변경: dir_fd 매개 변수가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.major(device, /)

Extract the device major number from a raw device number (usually the st_dev or st_rdev field from stat).

os.minor(device, /)

Extract the device minor number from a raw device number (usually the st_dev or st_rdev field from stat).

os.makedev(major, minor, /)

주 장치 번호와 부 장치 번호로 원시 장치 번호를 조립합니다.

os.pathconf(path, name)

이름있는 파일과 관련된 시스템 구성 정보를 반환합니다. name 은 조회할 구성 값을 지정합니다; 정의된 시스템 값의 이름인 문자열일 수 있습니다; 이 이름은 여러 표준(POSIX.1, 유닉스 95, 유닉스 98 및 기타)에서 지정됩니다. 일부 플랫폼은 추가적인 이름도 정의합니다. 호스트 운영 체제에 알려진 이름은 pathconf_names 딕셔너리에서 제공됩니다. 이 매핑에 포함되지 않은 구성 변수를 위해, name에 정수를 전달하는 것도 허용됩니다.

name 이 문자열이고 알 수 없으면, ValueError가 발생합니다. name에 대한 특정 값이 호스트 시스템에서 지원되지 않으면, pathconf_names에 포함되어 있어도, 에러 번호가 errno.EINVALOSError가 발생합니다.

이 함수는 파일 기술자 지정을 지원할 수 있습니다.

가용성: 유닉스.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.pathconf_names

pathconf()fpathconf()가 받아들이는 이름을 호스트 운영 체제에서 해당 이름에 대해 정의된 정숫값으로 매핑하는 딕셔너리. 이것은 시스템에 알려진 이름 집합을 판별하는 데 사용될 수 있습니다.

가용성: 유닉스.

심볼릭 링크가 가리키는 경로를 나타내는 문자열을 반환합니다. 결과는 절대 또는 상대 경로명일 수 있습니다; 상대 경로이면 os.path.join(os.path.dirname(path), result)를 사용하여 절대 경로명으로 변환할 수 있습니다.

path 가 (직접 또는 PathLike 인터페이스를 통해 간접적으로) 문자열 객체면, 결과도 문자열 객체가 되고, 호출은 UnicodeDecodeError를 발생시킬 수 있습니다. path 가 (직접 또는 간접적으로) 바이트열 객체면, 결과는 바이트열 객체가 됩니다.

이 기능은 디렉터리 기술자에 상대적인 경로도 지원할 수 있습니다.

링크를 포함할 수 있는 경로를 결정(resolve)하려고 할 때, realpath()를 사용하여 재귀와 플랫폼 차이를 올바르게 처리하십시오.

가용성: 유닉스, 윈도우.

버전 3.2에서 변경: 윈도우 6.0 (Vista) 심볼릭 링크에 대한 지원이 추가되었습니다.

버전 3.3에서 변경: dir_fd 매개 변수가 추가되었습니다.

버전 3.6에서 변경: 유닉스에서 경로류 객체를 받아들입니다.

버전 3.8에서 변경: 윈도우에서 경로류 객체와 바이트열 객체를 받아들입니다.

디렉터리 정션(directory junction)에 대한 지원이 추가되었고, 이전에 반환되던 선택적 “print name” 필드 대신 치환 경로(일반적으로 \\?\ 접두사를 포함합니다)를 반환하도록 변경되었습니다.

os.remove(path, *, dir_fd=None)

Remove (delete) the file path. If path is a directory, an OSError is raised. Use rmdir() to remove directories. If the file does not exist, a FileNotFoundError is raised.

이 함수는 디렉터리 기술자에 상대적인 경로를 지원할 수 있습니다.

윈도우에서, 사용 중인 파일을 제거하려고 시도하면 예외가 발생합니다; 유닉스에서는 디렉터리 항목이 제거되지만, 원본 파일이 더는 사용되지 않을 때까지 파일에 할당된 저장 공간을 사용할 수 없습니다.

이 함수는 의미 적으로 unlink()와 같습니다.

path, dir_fd를 인자로 감사 이벤트(auditing event) os.remove를 발생시킵니다.

버전 3.3에서 변경: dir_fd 매개 변수가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.removedirs(name)

재귀적으로 디렉터리를 제거합니다. rmdir() 처럼 동작하는데 다음과 같은 차이가 있습니다. 말단 디렉터리가 성공적으로 제거되면, removedirs()는 에러가 발생할 때까지 path에 언급된 모든 상위 디렉터리를 연속적으로 제거하려고 합니다 (에러는 무시되는데, 이는 일반적으로 부모 디렉터리가 비어 있음을 뜻하기 때문입니다). 예를 들어, os.removedirs('foo/bar/baz')는 먼저 'foo/bar/baz' 디렉터리를 제거한 다음, 'foo/bar''foo'가 비어 있으면 제거합니다. 말단 디렉터리를 성공적으로 제거할 수 없으면, OSError를 발생시킵니다.

path, dir_fd를 인자로 감사 이벤트(auditing event) os.remove를 발생시킵니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

파일 또는 디렉터리 src의 이름을 dst로 바꿉니다. dst가 존재하면, 많은 경우에 OSError 서브 클래스로 연산이 실패합니다:

On Windows, if dst exists a FileExistsError is always raised. The operation may fail if src and dst are on different filesystems. Use shutil.move() to support moves to a different filesystem.

On Unix, if src is a file and dst is a directory or vice-versa, an IsADirectoryError or a NotADirectoryError will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, an OSError is raised. If both are files, dst will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

이 함수는 디렉터리 기술자에 상대적인 경로를 제공하도록 src_dir_fd 와/나 dst_dir_fd 를 지정하는 것을 지원할 수 있습니다.

플랫폼에 무관하게 대상을 덮어쓰길 원하면, replace()를 사용하십시오.

src, dst, src_dir_fd, dst_dir_fd를 인자로 감사 이벤트(auditing event) os.rename을 발생시킵니다.

버전 3.3에서 변경: Added the src_dir_fd and dst_dir_fd parameters.

버전 3.6에서 변경: srcdst경로류 객체를 받아들입니다.

os.renames(old, new)

재귀적 디렉터리 또는 파일 이름 바꾸기 함수. rename()처럼 작동하지만, 새 경로명이 유효하도록 만들기 위해 먼저 필요한 중간 디렉터리를 만드는 점이 다릅니다. 이름을 변경한 후에는, 이전 이름의 가장 오른쪽 경로 세그먼트에 해당하는 디렉터리를 removedirs()를 사용하여 제거합니다.

참고

이 함수는 말단 디렉터리나 파일을 제거하는 데 필요한 권한이 없을 때, 새 디렉터리 구조를 만든 상태에서 실패할 수 있습니다.

src, dst, src_dir_fd, dst_dir_fd를 인자로 감사 이벤트(auditing event) os.rename을 발생시킵니다.

버전 3.6에서 변경: oldnew경로류 객체를 받아들입니다.

os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

Rename the file or directory src to dst. If dst is a non-empty directory, OSError will be raised. If dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

이 함수는 디렉터리 기술자에 상대적인 경로를 제공하도록 src_dir_fd 와/나 dst_dir_fd 를 지정하는 것을 지원할 수 있습니다.

src, dst, src_dir_fd, dst_dir_fd를 인자로 감사 이벤트(auditing event) os.rename을 발생시킵니다.

버전 3.3에 추가.

버전 3.6에서 변경: srcdst경로류 객체를 받아들입니다.

os.rmdir(path, *, dir_fd=None)

Remove (delete) the directory path. If the directory does not exist or is not empty, a FileNotFoundError or an OSError is raised respectively. In order to remove whole directory trees, shutil.rmtree() can be used.

이 함수는 디렉터리 기술자에 상대적인 경로를 지원할 수 있습니다.

path, dir_fd를 인자로 감사 이벤트(auditing event) os.rmdir을 발생시킵니다.

버전 3.3에서 변경: dir_fd 매개 변수가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.scandir(path='.')

path로 지정된 디렉터리 내의 항목에 대응하는 os.DirEntry 객체의 이터레이터를 돌려줍니다. 항목은 임의의 순서로 제공되며, 특수 항목 '.''..'는 포함되지 않습니다. 이터레이터를 만든 후에 디렉터리에서 파일이 제거되거나 추가되면, 해당 파일의 항목이 포함되는지는 지정되지 않습니다.

listdir() 대신 scandir()를 사용하면, 디렉터리를 검색할 때 운영 체제가 제공한다면 os.DirEntry 객체가 파일 유형과 파일 어트리뷰트 정보를 제공하기 때문에, 이것들이 필요한 코드의 성능을 크게 개선할 수 있습니다. 모든 os.DirEntry 메서드가 시스템 호출을 수행할 수 있지만, 일반적으로 is_dir()is_file()는 심볼릭 링크에 대해서만 시스템 호출을 요구합니다; os.DirEntry.stat()는 유닉스에서 항상 시스템 호출을 요구하지만 윈도우에서는 심볼릭 링크에 대해서만 시스템 호출을 요구합니다.

path경로류 객체 일 수 있습니다. path 가 (직접 또는 PathLike 인터페이스를 통해 간접적으로) bytes 형이면, 각 os.DirEntrynamepath 어트리뷰트의 형은 bytes입니다. 다른 모든 상황에서는 형 str이 됩니다.

이 함수는 또한 파일 기술자 지정을 지원할 수 있습니다; 파일 기술자는 디렉터리를 참조해야 합니다.

path를 인자로 감사 이벤트(auditing event) os.scandir을 발생시킵니다.

scandir() 이터레이터는 컨텍스트 관리자 프로토콜을 지원하고 다음과 같은 메서드를 제공합니다:

scandir.close()

이터레이터를 닫고 확보한 자원을 반납합니다.

이터레이터가 소진되거나 가비지 수집될 때 또는 이터레이션 중에 에러가 발생하면 자동으로 호출됩니다. 하지만 명시적으로 호출하거나 with 문을 사용하는 것이 좋습니다.

버전 3.6에 추가.

다음 예제는 주어진 path'.'로 시작하지 않는 모든 파일(디렉터리 제외)을 표시하기 위한 scandir()의 간단한 사용을 보여줍니다. entry.is_file() 호출은 일반적으로 추가 시스템 호출을 하지 않습니다:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)

참고

On Unix-based systems, scandir() uses the system’s opendir() and readdir() functions. On Windows, it uses the Win32 FindFirstFileW and FindNextFileW functions.

버전 3.5에 추가.

버전 3.6에서 변경: 컨텍스트 관리자 프로토콜과 close() 메서드 대한 지원이 추가되었습니다. scandir() 이터레이터가 모두 소진되거나 명시적으로 닫히지 않으면 ResourceWarning가 파괴자에서 방출됩니다.

이 함수는 경로류 객체를 받아들입니다.

버전 3.7에서 변경: 유닉스에서 파일 기술자에 대한 지원이 추가되었습니다.

class os.DirEntry

디렉터리 항목의 파일 경로와 다른 파일 어트리뷰트를 노출하기 위해 scandir()에 의해 산출되는 객체.

scandir()는 추가 시스템 호출 없이 가능한 많은 정보를 제공합니다. stat() 또는 lstat() 시스템 호출이 이루어지면, os.DirEntry 객체는 결과를 캐시 합니다.

os.DirEntry 인스턴스는 수명이 긴 데이터 구조에 저장하는 용도가 아닙니다; 파일 메타 데이터가 변경되었거나 scandir()를 호출한 후 오랜 시간이 지났음을 안다면, os.stat(entry.path)를 호출하여 최신 정보를 가져오십시오.

os.DirEntry 메서드는 운영 체제 시스템 호출을 할 수 있으므로, OSError를 일으킬 수도 있습니다. 에러에 대해 매우 세부적인 제어가 필요하면, os.DirEntry 메서드 중 하나를 호출할 때 OSError를 잡은 후 적절하게 처리할 수 있습니다.

경로류 객체로 직접 사용할 수 있도록, os.DirEntryPathLike 인터페이스를 구현합니다.

os.DirEntry 인스턴스의 어트리뷰트 및 메서드는 다음과 같습니다:

name

scandir() path 인자에 상대적인, 항목의 기본(base) 파일명.

name 어트리뷰트는 scandir() path 인자가 bytes 형이면 bytes 고, 그렇지 않으면 str 입니다. 바이트열 파일명을 디코딩하려면 fsdecode()를 사용하십시오.

path

항목의 전체 경로명: os.path.join(scandir_path, entry.name)과 같습니다. 여기서 scandir_pathscandir() path 인자입니다. 경로는 scandir() path 인자가 절대 경로일 때만 절대 경로입니다. scandir() path 인자가 파일 기술자면, path 어트리뷰트는 name 어트리뷰트와 같습니다.

path 어트리뷰트는 scandir() path 인자가 bytes 형이면 bytes고, 그렇지 않으면 str 입니다. 바이트열 파일명을 디코딩하려면 fsdecode()를 사용하십시오.

inode()

항목의 아이노드(inode) 번호를 반환합니다.

결과는 os.DirEntry 객체에 캐시 됩니다. 최신 정보를 가져오려면 os.stat(entry.path, follow_symlinks=False).st_ino를 사용하십시오.

최초의 캐시 되지 않은 호출에서, 윈도우 에서는 시스템 호출이 필요하지만, 유닉스에서는 그렇지 않습니다.

is_dir(*, follow_symlinks=True)

이 항목이 디렉터리 또는 디렉터리를 가리키는 심볼릭 링크면 True를 반환합니다; 항목이 다른 종류의 파일이거나 다른 종류의 파일을 가리키면, 또는 더는 존재하지 않으면 False를 반환합니다.

follow_symlinksFalse면, 이 항목이 디렉터리일 때만 (심볼릭 링크를 따르지 않고) True를 반환합니다; 항목이 다른 종류의 파일이거나 더는 존재하지 않으면 False를 반환합니다.

결과는 follow_symlinksTrueFalse일 때에 대해 별도로 os.DirEntry 객체에 캐시 됩니다. 최신 정보를 가져오려면, stat.S_ISDIR()os.stat()을 호출하십시오.

최초의 캐시 되지 않은 호출에서, 대부분 시스템 호출이 필요하지 않습니다. 특히, 심볼릭 링크가 아니면, 윈도우나 유닉스 모두 시스템 호출이 필요하지 않은데, 네트워크 파일 시스템과 같이 dirent.d_type == DT_UNKNOWN를 반환하는 특정 유닉스 파일 시스템은 예외입니다. 항목이 심볼릭 링크면, follow_symlinksFalse가 아닌 이상, 심볼릭 링크를 따르기 위해 시스템 호출이 필요합니다.

이 메서드는, PermissionError와 같은, OSError를 발생시킬 수 있지만, FileNotFoundError는 잡혀서 발생하지 않습니다.

is_file(*, follow_symlinks=True)

이 항목이 파일이나 파일을 가리키는 심볼릭 링크면 True를 반환합니다; 항목이 디렉터리 또는 다른 비 파일 항목이거나, 그런 것을 가리키거나, 더는 존재하지 않으면 False를 반환합니다.

follow_symlinksFalse면, 이 항목이 파일일 때만 (심볼릭 링크를 따르지 않고) True를 반환합니다; 항목이 디렉터리 나 다른 비 파일 항목이거나 더는 존재하지 않으면 False를 반환합니다.

결과는 os.DirEntry 객체에 캐시 됩니다. 캐싱, 시스템 호출, 예외 발생은 is_dir()과 같습니다.

이 항목이 심볼릭 링크면 (망가졌다 하더라도) True를 반환합니다; 항목이 디렉터리 나 어떤 종류의 파일이거나 더는 존재하지 않으면 False를 반환합니다.

결과는 os.DirEntry 객체에 캐시 됩니다. 최신 정보를 가져오려면 os.path.islink()를 호출하십시오.

첫 번째, 캐시 되지 않은 호출에서는 시스템 호출이 필요하지 않습니다. 특히 윈도우 나 유닉스는 dirent.d_type == DT_UNKNOWN를 반환하는 특정 유닉스 파일 시스템 (예 : 네트워크 파일 시스템)을 제외하고는 시스템 호출이 필요하지 않습니다.

이 메서드는, PermissionError와 같은, OSError를 발생시킬 수 있지만, FileNotFoundError는 잡혀서 발생하지 않습니다.

is_junction()

Return True if this entry is a junction (even if broken); return False if the entry points to a regular directory, any kind of file, a symlink, or if it doesn’t exist anymore.

The result is cached on the os.DirEntry object. Call os.path.isjunction() to fetch up-to-date information.

버전 3.12에 추가.

stat(*, follow_symlinks=True)

이 항목의 stat_result 객체를 돌려줍니다. 이 메서드는 기본적으로 심볼릭 링크를 따릅니다; 심볼릭 링크를 stat 하려면, follow_symlinks=False 인자를 추가하십시오.

유닉스에서, 이 메서드는 항상 시스템 호출을 요구합니다. 윈도우에서, follow_symlinksTrue이고 항목이 재해석 지점(reparse point, 예를 들어, 심볼릭 링크나 디렉터리 정션(directory junction))일 때만 시스템 호출이 필요합니다.

윈도우에서, stat_resultst_ino, st_devst_nlink 어트리뷰트는 항상 0으로 설정됩니다. 이러한 어트리뷰트를 얻으려면 os.stat()을 호출하십시오.

결과는 follow_symlinksTrueFalse일 때에 대해 별도로 os.DirEntry 객체에 캐시 됩니다. 최신 정보를 가져오려면, os.stat()을 호출하십시오.

Note that there is a nice correspondence between several attributes and methods of os.DirEntry and of pathlib.Path. In particular, the name attribute has the same meaning, as do the is_dir(), is_file(), is_symlink(), is_junction(), and stat() methods.

버전 3.5에 추가.

버전 3.6에서 변경: PathLike 인터페이스에 대한 지원이 추가되었습니다. 윈도우에서 bytes 경로에 대한 지원이 추가되었습니다.

버전 3.12에서 변경: The st_ctime attribute of a stat result is deprecated on Windows. The file creation time is properly available as st_birthtime, and in the future st_ctime may be changed to return zero or the metadata change time, if available.

os.stat(path, *, dir_fd=None, follow_symlinks=True)

파일 또는 파일 기술자의 상태를 가져옵니다. 주어진 경로에 대해 stat() 시스템 호출과 같은 작업을 수행합니다. path 는 문자열이나 바이트열 – 직접 또는 PathLike 인터페이스를 통해 간접적으로 – 또는 열린 파일 기술자로 지정될 수 있습니다. stat_result 객체를 반환합니다.

이 함수는 일반적으로 심볼릭 링크를 따릅니다; 심볼릭 링크를 stat 하려면, 인자 follow_symlinks=False를 추가하거나 lstat()를 사용하십시오.

이 함수는 파일 기술자 지정심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

윈도우에서, follow_symlinks=False를 전달하면 심볼릭 링크와 디렉터리 정션(directory junction)을 포함하는 모든 이름 서로게이트(name-surrogate) 재해석 지점(reparse point)을 따라가지 않습니다. 링크처럼 보이지 않거나 운영 체제에서 따라갈 수 없는 다른 유형의 재해석 지점은 직접 열립니다. 여러 링크 체인을 따라갈 때, 전체 탐색을 방해하는 비 링크 대신 원래 링크가 반환될 수 있습니다. 이 경우 최종 경로에 대한 stat 결과를 얻으려면, os.path.realpath() 함수를 사용하여 가능한 한 멀리 간 경로 이름을 확인한 다음 드 결과에 대해 lstat()을 호출하십시오. 매달린(dangling) 심볼릭 링크나 정션 지점에는 적용되지 않고, 일반적인 예외가 발생합니다.

예:

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264

더 보기

fstat()lstat() 함수.

버전 3.3에서 변경: Added the dir_fd and follow_symlinks parameters, specifying a file descriptor instead of a path.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.8에서 변경: 윈도우에서, 이제 운영 체제가 결정할 수 있는 모든 재해석 지점을 따라가고, follow_symlinks=False를 전달하면 모든 이름 서로게이트 재해석 지점을 따라가지 않습니다. 운영 체제가 따라갈 수 없는 재해석 지점에 도달하면, stat은 이제 에러를 발생시키는 대신 follow_symlinks=False가 지정된 것처럼 원래 경로에 대한 정보를 반환합니다.

class os.stat_result

Object whose attributes correspond roughly to the members of the stat structure. It is used for the result of os.stat(), os.fstat() and os.lstat().

어트리뷰트:

st_mode

파일 모드: 파일 유형 및 파일 모드 비트 (사용 권한).

st_ino

플랫폼에 따라 다르지만, 0이 아니면, 지정된 값의 st_dev은 파일을 고유하게 식별합니다. 일반적으로:

st_dev

이 파일이 있는 장치의 식별자.

하드 링크 수.

st_uid

파일 소유자의 사용자 식별자.

st_gid

파일 소유자의 그룹 식별자.

st_size

일반 파일 또는 심볼릭 링크면, 바이트 단위의 파일의 크기. 심볼릭 링크의 크기는 포함하고 있는 경로명의 길이이며, 끝나는 널 바이트는 포함하지 않습니다.

타임스탬프:

st_atime

초 단위의 가장 최근의 액세스 시간.

st_mtime

초 단위의 가장 최근의 내용 수정 시간.

st_ctime

Time of most recent metadata change expressed in seconds.

버전 3.12에서 변경: st_ctime is deprecated on Windows. Use st_birthtime for the file creation time. In the future, st_ctime will contain the time of the most recent metadata change, as for other platforms.

st_atime_ns

나노초 정수 단위의 가장 최근의 액세스 시간.

버전 3.3에 추가.

st_mtime_ns

나노초 정수 단위의 가장 최근의 내용 수정 시간.

버전 3.3에 추가.

st_ctime_ns

Time of most recent metadata change expressed in nanoseconds as an integer.

버전 3.3에 추가.

버전 3.12에서 변경: st_ctime_ns is deprecated on Windows. Use st_birthtime_ns for the file creation time. In the future, st_ctime will contain the time of the most recent metadata change, as for other platforms.

st_birthtime

Time of file creation expressed in seconds. This attribute is not always available, and may raise AttributeError.

버전 3.12에서 변경: st_birthtime is now available on Windows.

st_birthtime_ns

Time of file creation expressed in nanoseconds as an integer. This attribute is not always available, and may raise AttributeError.

버전 3.12에 추가.

참고

The exact meaning and resolution of the st_atime, st_mtime, st_ctime and st_birthtime attributes depend on the operating system and the file system. For example, on Windows systems using the FAT32 file systems, st_mtime has 2-second resolution, and st_atime has only 1-day resolution. See your operating system documentation for details.

Similarly, although st_atime_ns, st_mtime_ns, st_ctime_ns and st_birthtime_ns are always expressed in nanoseconds, many systems do not provide nanosecond precision. On systems that do provide nanosecond precision, the floating-point object used to store st_atime, st_mtime, st_ctime and st_birthtime cannot preserve all of it, and as such will be slightly inexact. If you need the exact timestamps you should always use st_atime_ns, st_mtime_ns, st_ctime_ns and st_birthtime_ns.

(리눅스와 같은) 일부 유닉스 시스템에서는, 다음 어트리뷰트도 사용할 수 있습니다:

st_blocks

파일에 할당된 512-바이트 블록 수. 파일에 구멍이 있으면 st_size/512보다 작을 수 있습니다.

st_blksize

효율적인 파일 시스템 I/O를 위해 “선호되는” 블록 크기. 더 작은 크기로 파일에 기록하면 비효율적인 읽기-수정-다시 쓰기가 발생할 수 있습니다.

st_rdev

아이노드 장치면 장치 유형.

st_flags

파일에 대한 사용자 정의 플래그.

(FreeBSD와 같은) 다른 유닉스 시스템에서는, 다음 어트리뷰트를 사용할 수 있습니다 (그러나 root가 사용하려고 할 때만 채워질 수 있습니다):

st_gen

파일 생성 번호.

Solaris 및 파생 상품에서, 다음 어트리뷰트도 사용할 수 있습니다:

st_fstype

파일을 포함하는 파일 시스템의 유형을 고유하게 식별하는 문자열.

On macOS systems, the following attributes may also be available:

st_rsize

파일의 실제 크기.

st_creator

파일의 생성자.

st_type

파일 유형.

윈도우 시스템에서는, 다음 어트리뷰트도 사용할 수 있습니다:

st_file_attributes

Windows file attributes: dwFileAttributes member of the BY_HANDLE_FILE_INFORMATION structure returned by GetFileInformationByHandle(). See the FILE_ATTRIBUTE_* <stat.FILE_ATTRIBUTE_ARCHIVE> constants in the stat module.

버전 3.5에 추가.

st_reparse_tag

When st_file_attributes has the FILE_ATTRIBUTE_REPARSE_POINT set, this field contains the tag identifying the type of reparse point. See the IO_REPARSE_TAG_* constants in the stat module.

The standard module stat defines functions and constants that are useful for extracting information from a stat structure. (On Windows, some items are filled with dummy values.)

For backward compatibility, a stat_result instance is also accessible as a tuple of at least 10 integers giving the most important (and portable) members of the stat structure, in the order st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. More items may be added at the end by some implementations. For compatibility with older Python versions, accessing stat_result as a tuple always returns integers.

버전 3.5에서 변경: 윈도우는 이제 사용 가능할 때 파일 인덱스를 st_ino로 반환합니다.

버전 3.7에서 변경: Solaris/파생 제품에 st_fstype 멤버를 추가했습니다.

버전 3.8에서 변경: 윈도우에서 st_reparse_tag 멤버를 추가했습니다.

버전 3.8에서 변경: 윈도우에서, st_mode 멤버는 이제 특수 파일을 S_IFCHR, S_IFIFO 또는 S_IFBLK로 적절히 식별합니다.

버전 3.12에서 변경: On Windows, st_ctime is deprecated. Eventually, it will contain the last metadata change time, for consistency with other platforms, but for now still contains creation time. Use st_birthtime for the creation time.

On Windows, st_ino may now be up to 128 bits, depending on the file system. Previously it would not be above 64 bits, and larger file identifiers would be arbitrarily packed.

On Windows, st_rdev no longer returns a value. Previously it would contain the same as st_dev, which was incorrect.

Added the st_birthtime member on Windows.

os.statvfs(path)

Perform a statvfs() system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the statvfs structure, namely: f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax, f_fsid.

f_flag 어트리뷰트의 비트 플래그에 대해 두 개의 모듈 수준 상수가 정의됩니다: ST_RDONLY가 설정되면, 파일 시스템은 읽기 전용으로 마운트되었고, ST_NOSUID가 설정되면, setuid/setgid 비트의 의미가 비활성화되었거나 지원되지 않습니다.

추가적인 모듈 수준 상수가 GNU/glibc 기반 시스템에 대해 정의됩니다. 이들은 ST_NODEV (장치 특수 파일에 대한 액세스 금지), ST_NOEXEC (프로그램 실행 금지), ST_SYNCHRONOUS (한 번에 쓰기 동기화), ST_MANDLOCK (FS에 필수 잠금 허용), ST_WRITE (파일/디렉터리/심볼릭 링크 쓰기), ST_APPEND (덧붙이기 전용 파일), ST_IMMUTABLE (불변 파일), ST_NOATIME (액세스 시간을 갱신하지 않음), ST_NODIRATIME (디렉터리 액세스 시간을 갱신하지 않음), ST_RELATIME (mtime/ctime에 상대적으로 atime을 갱신).

이 함수는 파일 기술자 지정을 지원할 수 있습니다.

가용성: 유닉스.

버전 3.2에서 변경: ST_RDONLYST_NOSUID 상수가 추가되었습니다.

버전 3.3에서 변경: path에 열린 파일 기술자를 지정하는 지원이 추가되었습니다.

버전 3.4에서 변경: ST_NODEV, ST_NOEXEC, ST_SYNCHRONOUS, ST_MANDLOCK, ST_WRITE, ST_APPEND, ST_IMMUTABLE, ST_NOATIME, ST_NODIRATIMEST_RELATIME 상수가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.7에서 변경: Added the f_fsid attribute.

os.supports_dir_fd

os 모듈의 어떤 함수가 dir_fd 매개 변수로 열린 파일 기술자를 받아들이는지를 나타내는 set 객체. 플랫폼마다 다른 기능을 제공하며, 파이썬이 dir_fd 매개 변수를 구현하는 데 사용하는 하부 기능이 파이썬이 지원하는 모든 플랫폼에서 제공되지는 않습니다. 일관성을 위해, dir_fd 를 지원할 수도 있는 함수는 항상 매개 변수를 지정할 수 있도록 하지만, 로컬에서 사용할 수 없을 때, 기능을 사용하면 예외를 발생시킵니다. (dir_fdNone을 지정하는 것은 모든 플랫폼에서 항상 지원됩니다.)

특정 함수가 dir_fd 매개 변수로 열린 파일 기술자를 받아들이는지 확인하려면, supports_dir_fdin 연산자를 사용하십시오. 예를 들어, 이 표현식은 로컬 플랫폼에서 os.stat()dir_fd 매개 변수로 열린 파일 기술자를 받아들이면 True로 평가됩니다:

os.stat in os.supports_dir_fd

현재 dir_fd 매개 변수는 유닉스 플랫폼에서만 작동합니다; 어느 것도 윈도우에서 작동하지 않습니다.

버전 3.3에 추가.

os.supports_effective_ids

os.access()가 로컬 플랫폼에서 effective_ids 매개 변수에 True를 지정하는 것을 허용하는지를 나타내는 set 객체. (effective_idsFalse를 지정하는 것은 모든 플랫폼에서 항상 지원됩니다.) 로컬 플랫폼이 지원하면, 컬렉션에 os.access()가 포함됩니다; 그렇지 않으면 비어있게 됩니다.

이 표현식은 로컬 플랫폼에서 os.access()effective_ids=True를 지원하면 True로 평가됩니다:

os.access in os.supports_effective_ids

현재 effective_ids 는 유닉스 플랫폼에서만 지원됩니다; 윈도우에서는 작동하지 않습니다.

버전 3.3에 추가.

os.supports_fd

os 모듈의 어떤 함수가 로컬 플랫폼에서 자신의 path 매개 변수에 열린 파일 기술자를 지정하는 것을 허용하는지를 나타내는 set 객체. 플랫폼마다 다른 기능을 제공하며, 파이썬이 path로 열린 파일 기술자를 받아들이는 데 사용하는 하부 기능이 파이썬이 지원하는 모든 플랫폼에서 제공되지는 않습니다.

특정 함수가 path 매개 변수에 열린 파일 기술자를 지정할 수 있도록 허용하는지를 판단하려면, supports_fdin 연산자를 사용하십시오. 예를 들어, 이 표현식은 로컬 플랫폼에서 os.chdir()path로 열린 파일 기술자를 받아들이면 True로 평가됩니다:

os.chdir in os.supports_fd

버전 3.3에 추가.

os 모듈의 어떤 함수가 follow_symlinks 매개 변수로 False를 받아들이는지를 나타내는 set 객체. 플랫폼마다 다른 기능을 제공하며, 파이썬이 follow_symlinks를 구현하는 데 사용하는 하부 기능이 파이썬이 지원하는 모든 플랫폼에서 제공되지는 않습니다. 일관성을 위해, follow_symlinks 를 지원할 수도 있는 함수는 항상 매개 변수를 지정할 수 있도록 하지만, 로컬에서 사용할 수 없을 때, 기능이 사용되면 예외를 발생시킵니다. (follow_symlinksNone을 지정하는 것은 모든 플랫폼에서 항상 지원됩니다.)

특정 함수가 follow_symlinks 매개 변수로 False를 받아들이는지 확인하려면, supports_follow_symlinksin 연산자를 사용하십시오. 예를 들어, 이 표현식은 로컬 플랫폼에서 os.stat()을 호출할 때 follow_symlinks=False를 지정할 수 있으면 True로 평가됩니다:

os.stat in os.supports_follow_symlinks

버전 3.3에 추가.

src를 가리키는 dst 라는 이름의 심볼릭 링크를 만듭니다.

윈도우에서, 심볼릭 링크는 파일이나 디렉터리를 나타내며, 동적으로 대상에 맞춰 변형되지 않습니다. 대상이 있으면, 일치하도록 심볼릭 링크의 유형이 만들어집니다. 그렇지 않으면, target_is_directoryTrue 면 심볼릭 링크가 디렉터리로 만들어지고, 그렇지 않으면 파일 심볼릭 링크(기본값)가 만들어집니다. 비 윈도우 플랫폼에서는 target_is_directory 가 무시됩니다.

이 함수는 디렉터리 기술자에 상대적인 경로를 지원할 수 있습니다.

참고

최신 버전의 윈도우 10에서, 개발자 모드가 활성화되면, 권한이 없는 계정이 심볼릭 링크를 만들 수 있습니다. 개발자 모드를 사용할 수 없거나 활성화되어 있지 않으면, SeCreateSymbolicLinkPrivilege 권한이 필요하거나, 프로세스를 관리자로 실행해야 합니다.

권한이 없는 사용자가 함수를 호출하면 OSError가 발생합니다.

src, dst, dir_fd를 인자로 감사 이벤트(auditing event) os.symlink를 발생시킵니다.

가용성: 유닉스, 윈도우.

The function is limited on Emscripten and WASI, see WebAssembly platforms for more information.

버전 3.2에서 변경: 윈도우 6.0 (Vista) 심볼릭 링크에 대한 지원이 추가되었습니다.

버전 3.3에서 변경: Added the dir_fd parameter, and now allow target_is_directory on non-Windows platforms.

버전 3.6에서 변경: srcdst경로류 객체를 받아들입니다.

버전 3.8에서 변경: 개발자 모드가 있는 윈도우에서 권한 상승 없는(unelevated) 심볼릭 링크에 대한 지원이 추가되었습니다.

os.sync()

디스크에 모든 것을 쓰도록 강제합니다.

가용성: 유닉스.

버전 3.3에 추가.

os.truncate(path, length)

최대 length 바이트가 되도록 path에 해당하는 파일을 자릅니다.

이 함수는 파일 기술자 지정을 지원할 수 있습니다.

path, length를 인자로 감사 이벤트(auditing event) os.truncate를 발생시킵니다.

가용성: 유닉스, 윈도우.

버전 3.3에 추가.

버전 3.5에서 변경: 윈도우 지원 추가

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

파일 path를 제거(삭제)합니다. 이 함수는 의미상 remove()와 같습니다; unlink 라는 이름은 전통적인 유닉스 이름입니다. 자세한 내용은 remove() 설명서를 참조하십시오.

path, dir_fd를 인자로 감사 이벤트(auditing event) os.remove를 발생시킵니다.

버전 3.3에서 변경: dir_fd 매개 변수가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.utime(path, times=None, *, [ns, ]dir_fd=None, follow_symlinks=True)

path로 지정된 파일의 액세스 및 수정 시간을 설정합니다.

utime()timesns 라는 두 개의 선택적 매개 변수를 취합니다. path에 설정할 시간을 지정하며 다음과 같이 사용됩니다:

  • ns 가 지정되면, (atime_ns, mtime_ns) 형식의 2-튜플이어야 하며, 각 멤버는 나노초를 나타내는 int입니다.

  • timesNone이 아니면, (atime, mtime) 형식의 2-튜플이어야 하며, 각 멤버는 초를 나타내는 int 또는 float입니다.

  • timesNone이고 ns 가 지정되지 않으면, ns=(atime_ns, mtime_ns)를 지정하는 것과 같은데, 두 시간 모두 현재 시각입니다.

timesns에 모두 튜플을 지정하는 것은 에러입니다.

Note that the exact times you set here may not be returned by a subsequent stat() call, depending on the resolution with which your operating system records access and modification times; see stat(). The best way to preserve exact times is to use the st_atime_ns and st_mtime_ns fields from the os.stat() result object with the ns parameter to utime().

이 함수는 파일 기술자 지정, 디렉터리 기술자에 상대적인 경로심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

path, times, ns, dir_fd를 인자로 감사 이벤트(auditing event) os.utime을 발생시킵니다.

버전 3.3에서 변경: path에 열린 파일 기술자를 지정하는 것과 dir_fd , follow_symlinksns 매개 변수 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.walk(top, topdown=True, onerror=None, followlinks=False)

트리를 하향식 또는 상향식으로 탐색하여 디렉터리 트리에 있는 파일명을 생성합니다. 디렉터리 top을 루트로 하는 트리의 디렉터리(top 자체를 포함합니다)마다, 3-튜플 (dirpath, dirnames, filenames)를 산출합니다.

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (including symlinks to directories, and excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). Whether or not the lists are sorted depends on the file system. If a file is removed from or added to the dirpath directory during generating the lists, whether a name for that file be included is unspecified.

선택적 인자 topdownTrue이거나 지정되지 않으면, 디렉터리에 대한 3-튜플은 하위 디렉터리에 대한 3-튜플이 생성되기 전에 생성됩니다 (디렉터리는 하향식으로 생성됩니다). topdownFalse면, 모든 하위 디렉터리에 대한 3-튜플 다음에 디렉터리에 대한 3-튜플이 생성됩니다 (디렉터리가 상향식으로 생성됨). topdown 의 값에 상관없이, 디렉터리와 해당 하위 디렉터리의 튜플이 생성되기 전에 하위 디렉터리 목록이 조회됩니다.

topdownTrue 일 때, 호출자는 (아마도 del 또는 슬라이스 대입을 사용하여) dirnames 리스트를 수정할 수 있으며, walk()는 이름이 dirnames 남아있는 하위 디렉터리로만 재귀합니다; 검색을 가지치기하거나, 특정 방문 순서를 지정하거나, 심지어 walk()가 다시 시작하기 전에 호출자가 새로 만들거나 이름을 바꾼 디렉터리에 대해 walk()에 알릴 때도 사용할 수 있습니다. topdownFalse일 때 dirnames를 수정하는 것은 walk의 동작에 영향을 주지 못하는데, 상향식 모드에서 dirnames의 디렉터리는 dirpath 자체가 생성되기 전에 생성되기 때문입니다.

기본적으로, scandir() 호출의 에러는 무시됩니다. 선택적 인자 onerror 가 지정되면, 함수여야 합니다; 하나의 인자 OSError 인스턴스로 호출됩니다. 에러를 보고하고 walk를 계속하도록 하거나, 예외를 발생시켜 walk를 중단할 수 있습니다. 파일명은 예외 객체의 filename 어트리뷰트로 제공됩니다.

기본적으로, walk()는 디렉터리로 해석되는 심볼릭 링크로 이동하지 않습니다. 지원하는 시스템에서, 심볼릭 링크가 가리키는 디렉터리를 방문하려면, followlinksTrue로 설정하십시오.

참고

심볼릭 링크가 자신의 부모 디렉터리를 가리킬 때, followlinksTrue로 설정하면 무한 재귀가 발생할 수 있음에 주의해야 합니다. walk()는 이미 방문한 디렉터리를 추적하지 않습니다.

참고

상대 경로명을 전달할 때는, walk()가 실행되는 도중 현재 작업 디렉터리를 변경하지 마십시오. walk()는 현재 디렉터리를 절대로 변경하지 않으며, 호출자도 마찬가지라고 가정합니다.

이 예는 시작 디렉터리 아래의 각 디렉터리에 있는 비 디렉터리 파일이 차지한 바이트 수를 표시합니다. 단, CVS 하위 디렉터리 아래는 보지 않습니다:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print(root, "consumes", end=" ")
    print(sum(getsize(join(root, name)) for name in files), end=" ")
    print("bytes in", len(files), "non-directory files")
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

다음 예(shutil.rmtree()의 간단한 구현)에서는, 트리를 상향식으로 탐색하는 것이 필수적입니다, rmdir()는 비어 있지 않은 디렉터리를 삭제할 수 없습니다:

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

top, topdown, onerror, followlinks를 인자로 감사 이벤트(auditing event) os.walk를 발생시킵니다.

버전 3.5에서 변경: 이 함수는 이제 os.listdir() 대신 os.scandir()를 호출하기 때문에, os.stat() 호출 수를 줄여 더 빨라졌습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)

이 함수는 walk()와 똑같이 동작합니다. 단, 4-튜플 (dirpath, dirnames, filenames, dirfd)를 산출하고 dir_fd를 지원합니다.

dirpath , dirnamesfilenameswalk() 출력과 같고, dirfddirpath 디렉터리를 가리키는 파일 기술자입니다.

이 함수는 항상 디렉터리 기술자에 상대적인 경로심볼릭 링크를 따르지 않음을 지원합니다. 하지만, 다른 함수와는 달리, follow_symlinks에 대한 fwalk()의 기본값은 False임에 주의하십시오.

참고

fwalk()는 다음 이터레이션 단계까지만 유효한 파일 기술자를 산출하기 때문에, 더 오래 유지하려면 복제해야 합니다 (예를 들어, dup()로).

이 예는 시작 디렉터리 아래의 각 디렉터리에 있는 비 디렉터리 파일이 차지한 바이트 수를 표시합니다. 단, CVS 하위 디렉터리 아래는 보지 않습니다:

import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
    print(root, "consumes", end="")
    print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
          end="")
    print("bytes in", len(files), "non-directory files")
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

다음 예에서는, 트리를 상향식으로 탐색하는 것이 필수적입니다: rmdir()는 비어 있지 않은 디렉터리를 삭제할 수 없습니다:

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
    for name in files:
        os.unlink(name, dir_fd=rootfd)
    for name in dirs:
        os.rmdir(name, dir_fd=rootfd)

top, topdown, onerror, follow_symlinks, dir_fd를 인자로 감사 이벤트(auditing event) os.fwalk를 발생시킵니다.

가용성: 유닉스.

버전 3.3에 추가.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.7에서 변경: bytes 경로에 대한 지원이 추가되었습니다.

os.memfd_create(name[, flags=os.MFD_CLOEXEC])

익명 파일을 만들고 이를 가리키는 파일 기술자를 반환합니다. flags는 시스템에서 사용할 수 있는 os.MFD_* 상수(또는 이들의 비트별 OR 조합) 중 하나여야 합니다. 기본적으로, 새 파일 기술자는 상속 불가능합니다.

name에 제공된 이름은 파일명으로 사용되며 해당 심볼릭 링크의 대상으로 /proc/self/fd/ 디렉터리에 표시됩니다. 표시된 이름에는 항상 memfd: 접두어가 붙으며 디버깅 목적으로만 사용됩니다. 이름은 파일 기술자의 동작에 영향을 미치지 않고, 여러 파일이 부작용 없이 같은 이름을 가질 수 있습니다.

Availability: Linux >= 3.17 with glibc >= 2.27.

버전 3.8에 추가.

os.MFD_CLOEXEC
os.MFD_ALLOW_SEALING
os.MFD_HUGETLB
os.MFD_HUGE_SHIFT
os.MFD_HUGE_MASK
os.MFD_HUGE_64KB
os.MFD_HUGE_512KB
os.MFD_HUGE_1MB
os.MFD_HUGE_2MB
os.MFD_HUGE_8MB
os.MFD_HUGE_16MB
os.MFD_HUGE_32MB
os.MFD_HUGE_256MB
os.MFD_HUGE_512MB
os.MFD_HUGE_1GB
os.MFD_HUGE_2GB
os.MFD_HUGE_16GB

이 플래그들은 memfd_create()로 전달될 수 있습니다.

Availability: Linux >= 3.17 with glibc >= 2.27

The MFD_HUGE* flags are only available since Linux 4.14.

버전 3.8에 추가.

os.eventfd(initval[, flags=os.EFD_CLOEXEC])

Create and return an event file descriptor. The file descriptors supports raw read() and write() with a buffer size of 8, select(), poll() and similar. See man page eventfd(2) for more information. By default, the new file descriptor is non-inheritable.

initval is the initial value of the event counter. The initial value must be an 32 bit unsigned integer. Please note that the initial value is limited to a 32 bit unsigned int although the event counter is an unsigned 64 bit integer with a maximum value of 264-2.

flags can be constructed from EFD_CLOEXEC, EFD_NONBLOCK, and EFD_SEMAPHORE.

If EFD_SEMAPHORE is specified and the event counter is non-zero, eventfd_read() returns 1 and decrements the counter by one.

If EFD_SEMAPHORE is not specified and the event counter is non-zero, eventfd_read() returns the current event counter value and resets the counter to zero.

If the event counter is zero and EFD_NONBLOCK is not specified, eventfd_read() blocks.

eventfd_write() increments the event counter. Write blocks if the write operation would increment the counter to a value larger than 264-2.

예:

import os

# semaphore with start value '1'
fd = os.eventfd(1, os.EFD_SEMAPHORE | os.EFC_CLOEXEC)
try:
    # acquire semaphore
    v = os.eventfd_read(fd)
    try:
        do_work()
    finally:
        # release semaphore
        os.eventfd_write(fd, v)
finally:
    os.close(fd)

Availability: Linux >= 2.6.27 with glibc >= 2.8

버전 3.10에 추가.

os.eventfd_read(fd)

Read value from an eventfd() file descriptor and return a 64 bit unsigned int. The function does not verify that fd is an eventfd().

Availability: Linux >= 2.6.27

버전 3.10에 추가.

os.eventfd_write(fd, value)

Add value to an eventfd() file descriptor. value must be a 64 bit unsigned int. The function does not verify that fd is an eventfd().

Availability: Linux >= 2.6.27

버전 3.10에 추가.

os.EFD_CLOEXEC

Set close-on-exec flag for new eventfd() file descriptor.

Availability: Linux >= 2.6.27

버전 3.10에 추가.

os.EFD_NONBLOCK

Set O_NONBLOCK status flag for new eventfd() file descriptor.

Availability: Linux >= 2.6.27

버전 3.10에 추가.

os.EFD_SEMAPHORE

Provide semaphore-like semantics for reads from a eventfd() file descriptor. On read the internal counter is decremented by one.

Availability: Linux >= 2.6.30

버전 3.10에 추가.

리눅스 확장 어트리뷰트

버전 3.3에 추가.

이 함수들은 모두 리눅스에서만 사용 가능합니다.

os.getxattr(path, attribute, *, follow_symlinks=True)

path의 확장 파일 시스템 어트리뷰트 attribute의 값을 반환합니다. attribute 는 bytes 또는 str(직접 또는 PathLike 인터페이스를 통해 간접적으로)일 수 있습니다. str이면, 파일 시스템 인코딩으로 인코딩됩니다.

이 함수는 파일 기술자 지정심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

path, attribute를 인자로 감사 이벤트(auditing event) os.getxattr을 발생시킵니다.

버전 3.6에서 변경: pathattribute에 대해 경로류 객체를 받아들입니다.

os.listxattr(path=None, *, follow_symlinks=True)

path 의 확장 파일 시스템 어트리뷰트 목록을 반환합니다. 목록의 어트리뷰트는 파일 시스템 인코딩으로 디코딩된 문자열로 표시됩니다. pathNone이면, listxattr()는 현재 디렉터리를 검사합니다.

이 함수는 파일 기술자 지정심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

path를 인자로 감사 이벤트(auditing event) os.listxattr을 발생시킵니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.removexattr(path, attribute, *, follow_symlinks=True)

Removes the extended filesystem attribute attribute from path. attribute should be bytes or str (directly or indirectly through the PathLike interface). If it is a string, it is encoded with the filesystem encoding and error handler.

이 함수는 파일 기술자 지정심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

path, attribute를 인자로 감사 이벤트(auditing event) os.removexattr을 발생시킵니다.

버전 3.6에서 변경: pathattribute에 대해 경로류 객체를 받아들입니다.

os.setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)

Set the extended filesystem attribute attribute on path to value. attribute must be a bytes or str with no embedded NULs (directly or indirectly through the PathLike interface). If it is a str, it is encoded with the filesystem encoding and error handler. flags may be XATTR_REPLACE or XATTR_CREATE. If XATTR_REPLACE is given and the attribute does not exist, ENODATA will be raised. If XATTR_CREATE is given and the attribute already exists, the attribute will not be created and EEXISTS will be raised.

이 함수는 파일 기술자 지정심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

참고

리눅스 커널 버전 2.6.39 미만의 버그로 인해 flags 인자가 일부 파일 시스템에서 무시되었습니다.

path, attribute, value, flags를 인자로 감사 이벤트(auditing event) os.setxattr을 발생시킵니다.

버전 3.6에서 변경: pathattribute에 대해 경로류 객체를 받아들입니다.

os.XATTR_SIZE_MAX

확장 어트리뷰트 값의 최대 크기입니다. 현재, 리눅스에서 64 KiB입니다.

os.XATTR_CREATE

이것은 setxattr()의 flags 인자를 위한 값입니다. 연산이 반드시 어트리뷰트를 새로 만들어야 함을 나타냅니다.

os.XATTR_REPLACE

이것은 setxattr()의 flags 인자를 위한 값입니다. 연산이 반드시 기존 어트리뷰트를 대체해야 함을 나타냅니다.

프로세스 관리

이 함수들은 프로세스를 만들고 관리하는데 사용될 수 있습니다.

다양한 exec* 함수는 프로세스로 로드되는 새 프로그램에 대한 인자 목록을 받아들입니다. 각각의 경우에, 첫 번째 인자는 사용자가 명령 줄에 입력할 수 있는 인자가 아닌 프로그램 자체의 이름으로 새 프로그램에 전달됩니다. C 프로그래머에게, 이것은 프로그램의 main()에 전달된 argv[0]입니다. 예를 들어, os.execv('/bin/echo', ['foo', 'bar'])는 표준 출력에 bar만 인쇄합니다; foo는 무시되는 것처럼 보이게 됩니다.

os.abort()

현재 프로세스에 SIGABRT 시그널을 생성합니다. 유닉스에서, 기본 동작은 코어 덤프를 생성하는 것입니다; 윈도우에서, 프로세스는 즉시 종료 코드 3을 반환합니다. 이 함수를 호출하면 signal.signal()를 사용하여 SIGABRT에 등록된 파이썬 시그널 처리기를 호출하지 않게 됨에 주의하시기 바랍니다.

os.add_dll_directory(path)

DLL 검색 경로에 path를 추가합니다.

This search path is used when resolving dependencies for imported extension modules (the module itself is resolved through sys.path), and also by ctypes.

반환된 객체의 close()를 호출하거나 반환된 객체를 with 문에서 사용하여 디렉터리를 제거하십시오.

DLL이 로드되는 방법에 대한 자세한 내용은 마이크로소프트 설명서를 참조하십시오.

path를 인자로 감사 이벤트(auditing event) os.add_dll_directory를 발생시킵니다.

가용성: 윈도우.

버전 3.8에 추가: 이전 버전의 CPython은 현재 프로세스의 기본 동작을 사용하여 DLL을 해결(resolve)합니다. 이로 인해 때때로 PATH나 현재 작업 디렉터리를 검색하거나, AddDllDirectory와 같은 OS 함수가 효과가 없게 되는 것과 같은 일관성 없는 결과를 낳습니다.

3.8에서는, 일관성을 보장하기 위해 이제 DLL이 로드되는 두 가지 기본 방법이 프로세스 전반의 동작을 명시적으로 재정의합니다. 라이브러리 갱신에 대한 정보는 이식 주의 사항을 참조하십시오.

os.execl(path, arg0, arg1, ...)
os.execle(path, arg0, arg1, ..., env)
os.execlp(file, arg0, arg1, ...)
os.execlpe(file, arg0, arg1, ..., env)
os.execv(path, args)
os.execve(path, args, env)
os.execvp(file, args)
os.execvpe(file, args, env)

이 함수들은 모두 현재 프로세스를 대체해서 새로운 프로그램을 실행합니다; 반환되지 않습니다. 유닉스에서, 새로운 실행 파일이 현재 프로세스에 로드되고, 호출자와 같은 프로세스 ID를 갖게 됩니다. 에러는 OSError 예외로 보고됩니다.

현재 프로세스가 즉시 교체됩니다. 열린 파일 객체와 기술자는 플러시 되지 않으므로, 이러한 열린 파일에 버퍼링 된 데이터가 있으면, exec* 함수를 호출하기 전에 sys.stdout.flush() 또는 os.fsync()를 사용하여 플러시 해야 합니다.

The “l” and “v” variants of the exec* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the execl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process should start with the name of the command being run, but this is not enforced.

The variants which include a “p” near the end (execlp(), execlpe(), execvp(), and execvpe()) will use the PATH environment variable to locate the program file. When the environment is being replaced (using one of the exec*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, execl(), execle(), execv(), and execve(), will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path. Relative paths must include at least one slash, even on Windows, as plain names will not be resolved.

execle(), execlpe(), execve(), execvpe()의 경우 (모두 “e”로 끝납니다), env 매개 변수는 새 프로세스의 환경 변수를 정의하는 데 사용되는 매핑이어야 합니다 (이것이 현재 프로세스의 환경 대신 사용됩니다); 함수 execl(), execlp(), execv()execvp()는 모두 새 프로세스가 현재 프로세스의 환경을 상속하게 합니다.

일부 플랫폼에서 execve()의 경우, path 는 열린 파일 기술자로도 지정될 수 있습니다. 이 기능은 여러분의 플랫폼에서 지원되지 않을 수 있습니다; os.supports_fd를 사용하여 사용할 수 있는지를 확인할 수 있습니다. 사용할 수 없을 때, 이를 사용하면 NotImplementedError가 발생합니다.

path, args, env를 인자로 감사 이벤트(auditing event) os.exec를 발생시킵니다.

Availability: Unix, Windows, not Emscripten, not WASI.

버전 3.3에서 변경: execve()path에 열린 파일 기술자를 지정하는 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os._exit(n)

상태 n으로 프로세스를 종료합니다. 클린업 처리기를 호출하거나, stdio 버퍼를 플러시 하거나 등등은 수행하지 않습니다.

참고

The standard way to exit is sys.exit(n). _exit() should normally only be used in the child process after a fork().

필수 조건은 아니지만, 다음 종료 코드가 정의되어 있으며 _exit()와 함께 사용할 수 있습니다. 이것은 메일 서버의 외부 명령 배달 프로그램과 같이 파이썬으로 작성된 시스템 프로그램에서 일반적으로 사용됩니다.

참고

약간의 차이점이 있어서, 이들 중 일부는 모든 유닉스 플랫폼에서 사용하지는 못할 수 있습니다. 이 상수는 하부 플랫폼에서 정의될 때만 정의됩니다.

os.EX_OK

Exit code that means no error occurred. May be taken from the defined value of EXIT_SUCCESS on some platforms. Generally has a value of zero.

가용성: 유닉스, 윈도우.

os.EX_USAGE

잘못된 개수의 인자가 제공된 경우처럼, 명령이 잘못 사용되었음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_DATAERR

입력 데이터가 잘못되었음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_NOINPUT

입력 파일이 없거나 읽을 수 없음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_NOUSER

지정된 사용자가 존재하지 않음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_NOHOST

지정된 호스트가 존재하지 않음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_UNAVAILABLE

필수 서비스를 사용할 수 없음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_SOFTWARE

내부 소프트웨어 에러가 감지되었음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_OSERR

포크 하거나 파이프를 만들 수 없는 등, 운영 체제 에러가 감지되었음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_OSFILE

일부 시스템 파일이 없거나, 열 수 없거나, 다른 에러가 있음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_CANTCREAT

사용자가 지정한 출력 파일을 만들 수 없음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_IOERR

일부 파일에서 I/O를 수행하는 동안 에러가 발생했음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_TEMPFAIL

임시 에러가 발생했음을 나타내는 종료 코드. 이는 재시도 가능한 작업 중에 만들 수 없었던 네트워크 연결과 같이 실제로는 에러가 아닐 수 있는 것을 나타냅니다.

Availability: Unix, not Emscripten, not WASI.

os.EX_PROTOCOL

프로토콜 교환이 불법이거나 유효하지 않거나 이해되지 않았음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_NOPERM

작업을 수행할 수 있는 권한이 충분하지 않음을 나타내는 종료 코드 (파일 시스템 문제에는 사용하지 않습니다).

Availability: Unix, not Emscripten, not WASI.

os.EX_CONFIG

어떤 종류의 구성 에러가 발생했음을 나타내는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.EX_NOTFOUND

“항목을 찾을 수 없습니다” 와 같은 것을 의미하는 종료 코드.

Availability: Unix, not Emscripten, not WASI.

os.fork()

자식 프로세스를 포크 합니다. 자식에서는 0을 반환하고, 부모에서는 자식의 프로세스 ID를 반환합니다. 에러가 발생하면 OSError를 일으킵니다.

FreeBSD <= 6.3 및 Cygwin을 포함한 일부 플랫폼은 스레드에서 fork()를 사용할 때 알려진 문제점이 있습니다.

인자 없이 감사 이벤트(auditing event) os.fork를 발생시킵니다.

경고

If you use TLS sockets in an application calling fork(), see the warning in the ssl documentation.

경고

On macOS the use of this function is unsafe when mixed with using higher-level system APIs, and that includes using urllib.request.

버전 3.8에서 변경: 서브 인터프리터에서 fork()를 호출하는 것은 더는 지원되지 않습니다 (RuntimeError가 발생합니다).

버전 3.12에서 변경: If Python is able to detect that your process has multiple threads, os.fork() now raises a DeprecationWarning.

We chose to surface this as a warning, when detectable, to better inform developers of a design problem that the POSIX platform specifically notes as not supported. Even in code that appears to work, it has never been safe to mix threading with os.fork() on POSIX platforms. The CPython runtime itself has always made API calls that are not safe for use in the child process when threads existed in the parent (such as malloc and free).

Users of macOS or users of libc or malloc implementations other than those typically found in glibc to date are among those already more likely to experience deadlocks running such code.

See this discussion on fork being incompatible with threads for technical details of why we’re surfacing this longstanding platform compatibility problem to developers.

Availability: POSIX, not Emscripten, not WASI.

os.forkpty()

새 의사 터미널을 자식의 제어 터미널로 사용하여 자식 프로세스를 포크 합니다. (pid, fd) 쌍을 반환하는데, 여기서 pid 는 자식에서 0이고, 부모에서는 새 자식의 프로세스 ID이고, fd 는 의사 터미널의 마스터 단의 파일 기술자입니다. 좀 더 이식성 있는 접근법을 사용하려면, pty 모듈을 사용하십시오. 에러가 발생하면 OSError를 일으킵니다.

인자 없이 감사 이벤트(auditing event) os.forkpty를 발생시킵니다.

경고

On macOS the use of this function is unsafe when mixed with using higher-level system APIs, and that includes using urllib.request.

버전 3.8에서 변경: 서브 인터프리터에서 forkpty()를 호출하는 것은 더는 지원되지 않습니다 (RuntimeError가 발생합니다).

버전 3.12에서 변경: If Python is able to detect that your process has multiple threads, this now raises a DeprecationWarning. See the longer explanation on os.fork().

Availability: Unix, not Emscripten, not WASI.

os.kill(pid, sig, /)

프로세스 pid에 시그널 sig를 보냅니다. 호스트 플랫폼에서 사용할 수 있는 구체적인 시그널에 대한 상수는 signal 모듈에 정의되어 있습니다.

Windows: The signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT signals are special signals which can only be sent to console processes which share a common console window, e.g., some subprocesses. Any other value for sig will cause the process to be unconditionally killed by the TerminateProcess API, and the exit code will be set to sig. The Windows version of kill() additionally takes process handles to be killed.

signal.pthread_kill()도 참조하십시오.

pid, sig를 인자로 감사 이벤트(auditing event) os.kill을 발생시킵니다.

Availability: Unix, Windows, not Emscripten, not WASI.

버전 3.2에서 변경: 윈도우 지원이 추가되었습니다.

os.killpg(pgid, sig, /)

시그널 sig 를 프로세스 그룹 pgid 로 보냅니다.

pgid, sig를 인자로 감사 이벤트(auditing event) os.killpg를 발생시킵니다.

Availability: Unix, not Emscripten, not WASI.

os.nice(increment, /)

프로세스의 “우선도(niceness)”에 increment 를 추가합니다. 새로운 우선도를 반환합니다.

Availability: Unix, not Emscripten, not WASI.

os.pidfd_open(pid, flags=0)

Return a file descriptor referring to the process pid with flags set. This descriptor can be used to perform process management without races and signals.

자세한 내용은 pidfd_open(2) 매뉴얼 페이지를 참조하십시오.

Availability: Linux >= 5.3

버전 3.9에 추가.

os.PIDFD_NONBLOCK

This flag indicates that the file descriptor will be non-blocking. If the process referred to by the file descriptor has not yet terminated, then an attempt to wait on the file descriptor using waitid(2) will immediately return the error EAGAIN rather than blocking.

Availability: Linux >= 5.10

버전 3.12에 추가.

os.plock(op, /)

프로그램 세그먼트를 메모리에 잠급니다. (<sys/lock.h>에서 정의된) op 값은 잠기는 세그먼트를 판별합니다.

Availability: Unix, not Emscripten, not WASI.

os.popen(cmd, mode='r', buffering=-1)

Open a pipe to or from command cmd. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The buffering argument have the same meaning as the corresponding argument to the built-in open() function. The returned file object reads or writes text strings rather than bytes.

close 메서드는 자식 프로세스가 성공적으로 종료되면 None을 반환하고, 에러가 있으면 자식 프로세스가 반환한 코드를 반환합니다. POSIX 시스템에서, 반환 코드가 양수면, 프로세스의 반환 값을 1바이트 왼쪽으로 시프트 한 값을 나타냅니다. 반환 코드가 음수면, 음의 반환 코드로 주어진 시그널에 의해 강제 종료된 것입니다. 예를 들어, 자식 프로세스가 죽었을(kill) 때 반환 값은 - signal.SIGKILL 일 수 있습니다. 윈도우 시스템에서, 반환 값은 자식 프로세스의 부호 있는 정수 반환 코드를 포함합니다.

유닉스에서, waitstatus_to_exitcode()None이 아닐 때 close 메서드 결과(종료 상태)를 종료 코드로 변환하는 데 사용할 수 있습니다. 윈도우에서, close 메서드 결과는 직접 종료 코드(또는 None)입니다.

이것은 subprocess.Popen를 사용하여 구현됩니다; 자식 프로세스를 관리하고 통신하는 보다 강력한 방법에 대해서는 이 클래스의 설명서를 참조하십시오.

Availability: not Emscripten, not WASI.

참고

The Python UTF-8 Mode affects encodings used for cmd and pipe contents.

popen() is a simple wrapper around subprocess.Popen. Use subprocess.Popen or subprocess.run() to control options like encodings.

os.posix_spawn(path, argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)

Wraps the posix_spawn() C library API for use from Python.

대부분 사용자는 posix_spawn() 대신 subprocess.run()을 사용해야 합니다.

위치 전용 인자 path, argsenvexecve()와 유사합니다.

path 매개 변수는 실행 파일의 경로입니다. path에는 디렉터리가 있어야 합니다. 디렉터리 없이 실행 파일을 전달하려면 posix_spawnp()를 사용하십시오.

file_actions 인자는 C 라이브러리 구현의 fork()exec() 단계 사이의 자식 프로세스에서 특정 파일 기술자에 취할 동작을 설명하는 튜플의 시퀀스 일 수 있습니다. 각 튜플의 첫 번째 항목은 나머지 튜플 요소를 설명하는, 아래에 나열된 세 가지 형 지시자 중 하나여야 합니다:

os.POSIX_SPAWN_OPEN

(os.POSIX_SPAWN_OPEN, fd, path, flags, mode)

os.dup2(os.open(path, flags, mode), fd)를 수행합니다.

os.POSIX_SPAWN_CLOSE

(os.POSIX_SPAWN_CLOSE, fd)

os.close(fd)를 수행합니다.

os.POSIX_SPAWN_DUP2

(os.POSIX_SPAWN_DUP2, fd, new_fd)

os.dup2(fd, new_fd)를 수행합니다.

These tuples correspond to the C library posix_spawn_file_actions_addopen(), posix_spawn_file_actions_addclose(), and posix_spawn_file_actions_adddup2() API calls used to prepare for the posix_spawn() call itself.

The setpgroup argument will set the process group of the child to the value specified. If the value specified is 0, the child’s process group ID will be made the same as its process ID. If the value of setpgroup is not set, the child will inherit the parent’s process group ID. This argument corresponds to the C library POSIX_SPAWN_SETPGROUP flag.

If the resetids argument is True it will reset the effective UID and GID of the child to the real UID and GID of the parent process. If the argument is False, then the child retains the effective UID and GID of the parent. In either case, if the set-user-ID and set-group-ID permission bits are enabled on the executable file, their effect will override the setting of the effective UID and GID. This argument corresponds to the C library POSIX_SPAWN_RESETIDS flag.

If the setsid argument is True, it will create a new session ID for posix_spawn. setsid requires POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP flag. Otherwise, NotImplementedError is raised.

The setsigmask argument will set the signal mask to the signal set specified. If the parameter is not used, then the child inherits the parent’s signal mask. This argument corresponds to the C library POSIX_SPAWN_SETSIGMASK flag.

The sigdef argument will reset the disposition of all signals in the set specified. This argument corresponds to the C library POSIX_SPAWN_SETSIGDEF flag.

The scheduler argument must be a tuple containing the (optional) scheduler policy and an instance of sched_param with the scheduler parameters. A value of None in the place of the scheduler policy indicates that is not being provided. This argument is a combination of the C library POSIX_SPAWN_SETSCHEDPARAM and POSIX_SPAWN_SETSCHEDULER flags.

path, argv, env를 인자로 감사 이벤트(auditing event) os.posix_spawn을 발생시킵니다.

버전 3.8에 추가.

Availability: Unix, not Emscripten, not WASI.

os.posix_spawnp(path, argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)

Wraps the posix_spawnp() C library API for use from Python.

시스템이 (execvp(3)과 같은 방식으로) PATH 환경 변수에 의해 지정된 디렉터리 목록에서 실행 파일을 검색한다는 점을 제외하고는 posix_spawn()과 유사합니다.

path, argv, env를 인자로 감사 이벤트(auditing event) os.posix_spawn을 발생시킵니다.

버전 3.8에 추가.

Availability: POSIX, not Emscripten, not WASI.

See posix_spawn() documentation.

os.register_at_fork(*, before=None, after_in_parent=None, after_in_child=None)

os.fork() 또는 유사한 프로세스 복제 API를 사용하여 새 자식 프로세스가 포크 될 때 실행될 콜러블들을 등록합니다. 매개 변수는 선택적이며 키워드 전용입니다. 각각은 다른 호출 지점을 지정합니다.

  • before 는 자식 프로세스를 포크 하기 전에 호출되는 함수입니다.

  • after_in_parent 는 자식 프로세스를 포크 한 후에 부모 프로세스에서 호출되는 함수입니다.

  • after_in_child 는 자식 프로세스에서 호출되는 함수입니다.

이러한 호출은 제거가 파이썬 인터프리터로 반환될 것으로 예상되는 경우에만 수행됩니다. 일반적인 subprocess 실행은 자식이 인터프리터로 재진입하지 않기 때문에, 이 호출들이 일어나지 않습니다.

포크 이전에 실행되도록 등록된 함수는 등록 역순으로 실행됩니다. 포크 후에 실행되도록 등록된 함수(부모나 자식 모두)는 등록 순서로 호출됩니다.

제삼자 C 코드에 의한 fork() 호출은, 그것이 명시적으로 PyOS_BeforeFork(), PyOS_AfterFork_Parent()PyOS_AfterFork_Child()를 호출하지 않는 한, 이 함수들을 호출하지 않습니다.

함수 등록을 취소할 방법은 없습니다.

Availability: Unix, not Emscripten, not WASI.

버전 3.7에 추가.

os.spawnl(mode, path, ...)
os.spawnle(mode, path, ..., env)
os.spawnlp(mode, file, ...)
os.spawnlpe(mode, file, ..., env)
os.spawnv(mode, path, args)
os.spawnve(mode, path, args, env)
os.spawnvp(mode, file, args)
os.spawnvpe(mode, file, args, env)

새 프로세스에서 프로그램 path 를 실행합니다.

(subprocess 모듈은 새 프로세스를 생성하고 결과를 조회하는데, 더욱 강력한 기능을 제공합니다; 이 모듈을 사용하는 것이 이 함수들을 사용하는 것보다 더 바람직합니다. 특히 이전 함수를 subprocess 모듈로 교체하기 섹션을 확인하십시오.)

modeP_NOWAIT면, 이 함수는 새 프로세스의 프로세스 ID를 반환합니다; modeP_WAIT면, 종료 코드(정상적으로 종료했을 때)나 -signal(signal은 프로세스를 죽인 시그널입니다)을 반환합니다. 윈도우에서, 프로세스 ID는 실제로 프로세스 핸들이므로, waitpid() 함수에 사용할 수 있습니다.

VxWorks에서, 이 함수는 새로운 프로세스가 죽을(kill) 때 -signal을 반환하지 않습니다. 대신 OSError 예외가 발생합니다.

The “l” and “v” variants of the spawn* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the spawnl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process must start with the name of the command being run.

끝 근처에 두 번째 “p”가 포함된 변형(spawnlp(), spawnlpe(), spawnvp()spawnvpe())은 PATH 환경 변수를 사용하여 프로그램 file 을 찾습니다. 환경이 대체 될 때 (다음 단락에서 설명할 spawn*e 변형 중 하나를 사용하여), 새 환경이 PATH 변수의 소스로 사용됩니다. 다른 변형 spawnl(), spawnle(), spawnv()spawnve()PATH 변수를 사용하여 실행 파일을 찾지 않습니다; path 에는 반드시 적절한 절대 또는 상대 경로가 있어야 합니다.

spawnle(), spawnlpe(), spawnve()spawnvpe()의 경우 (모두 “e”로 끝납니다), env 매개 변수는 새 프로세스의 환경 변수를 정의하는 데 사용되는 매핑이어야 합니다 (이것이 현재 프로세스의 환경 대신 사용됩니다); 함수 spawnl(), spawnlp(), spawnv()spawnvp()는 모두 새 프로세스가 현재 프로세스의 환경을 상속하게 합니다. env 딕셔너리의 키와 값은 반드시 문자열이어야 함에 주의하십시오; 잘못된 키나 값은 반환 값 127로 함수가 실패하게 합니다.

예를 들어, spawnlp()spawnvpe()에 대한 다음 호출은 동등합니다:

import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')

L = ['cp', 'index.html', '/dev/null']
os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)

mode, path, args, env를 인자로 감사 이벤트(auditing event) os.spawn을 발생시킵니다.

Availability: Unix, Windows, not Emscripten, not WASI.

spawnlp(), spawnlpe(), spawnvp() and spawnvpe() are not available on Windows. spawnle() and spawnve() are not thread-safe on Windows; we advise you to use the subprocess module instead.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.P_NOWAIT
os.P_NOWAITO

Possible values for the mode parameter to the spawn* family of functions. If either of these values is given, the spawn* functions will return as soon as the new process has been created, with the process id as the return value.

가용성: 유닉스, 윈도우.

os.P_WAIT

Possible value for the mode parameter to the spawn* family of functions. If this is given as mode, the spawn* functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or -signal if a signal kills the process.

가용성: 유닉스, 윈도우.

os.P_DETACH
os.P_OVERLAY

spawn* 계열 함수의 mode 매개 변수에 사용할 수 있는 값. 이들은 위에 나열된 것보다 이식성이 낮습니다. P_DETACHP_NOWAIT와 비슷하지만, 새 프로세스는 호출 프로세스의 콘솔에서 분리됩니다. P_OVERLAY가 사용되면, 현재 프로세스가 대체됩니다; spawn* 함수가 반환되지 않습니다.

가용성: 윈도우.

os.startfile(path[, operation][, arguments][, cwd][, show_cmd])

연관된 응용 프로그램으로 파일을 시작합니다.

When operation is not specified, this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.

When another operation is given, it must be a “command verb” that specifies what should be done with the file. Common verbs documented by Microsoft are 'open', 'print' and 'edit' (to be used on files) as well as 'explore' and 'find' (to be used on directories).

When launching an application, specify arguments to be passed as a single string. This argument may have no effect when using this function to launch a document.

The default working directory is inherited, but may be overridden by the cwd argument. This should be an absolute path. A relative path will be resolved against this argument.

Use show_cmd to override the default window style. Whether this has any effect will depend on the application being launched. Values are integers as supported by the Win32 ShellExecute() function.

startfile() returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application’s exit status. The path parameter is relative to the current directory or cwd. If you want to use an absolute path, make sure the first character is not a slash ('/') Use pathlib or the os.path.normpath() function to ensure that paths are properly encoded for Win32.

To reduce interpreter startup overhead, the Win32 ShellExecute() function is not resolved until this function is first called. If the function cannot be resolved, NotImplementedError will be raised.

path, operation을 인자로 감사 이벤트(auditing event) os.startfile을 발생시킵니다.

Raises an auditing event os.startfile/2 with arguments path, operation, arguments, cwd, show_cmd.

가용성: 윈도우.

버전 3.10에서 변경: Added the arguments, cwd and show_cmd arguments, and the os.startfile/2 audit event.

os.system(command)

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 return value of the Python function is system-dependent.

On Unix, the return value is the exit status of the process encoded in the format specified for wait().

윈도우에서, 반환 값은 command를 실행한 후 시스템 셸에서 반환한 값입니다. 셸은 윈도우 환경 변수 COMSPEC에 의해 제공됩니다: 보통 cmd.exe인데, 명령 실행의 종료 상태를 반환합니다; 기본이 아닌 셸을 사용하는 시스템에서는 셸 설명서를 참조하십시오.

subprocess 모듈은 새 프로세스를 생성하고 결과를 조회하는데, 더욱 강력한 기능을 제공합니다; 이 모듈을 사용하는 것이 이 함수들을 사용하는 것보다 더 바람직합니다. subprocess 설명서의 이전 함수를 subprocess 모듈로 교체하기 섹션에서 유용한 조리법을 확인하십시오.

유닉스에서, waitstatus_to_exitcode()를 사용하여 결과(종료 상태)를 종료 코드로 변환할 수 있습니다. 윈도우에서, 결과는 직접 종료 코드입니다.

command를 인자로 감사 이벤트(auditing event) os.system을 발생시킵니다.

Availability: Unix, Windows, not Emscripten, not WASI.

os.times()

현재 전역 프로세스 시간을 반환합니다. 반환 값은 5가지 어트리뷰트를 가진 객체입니다:

  • user - user time

  • system - system time

  • children_user - user time of all child processes

  • children_system - system time of all child processes

  • elapsed - elapsed real time since a fixed point in the past

For backwards compatibility, this object also behaves like a five-tuple containing user, system, children_user, children_system, and elapsed in that order.

See the Unix manual page times(2) and times(3) manual page on Unix or the GetProcessTimes MSDN on Windows. On Windows, only user and system are known; the other attributes are zero.

가용성: 유닉스, 윈도우.

버전 3.3에서 변경: 반환형이 튜플에서 이름이 지정된 어트리뷰트를 가진 튜플류 객체로 변경되었습니다.

os.wait()

자식 프로세스가 완료될 때까지 기다렸다가, pid 및 종료 상태 표시를 포함하는 튜플을 반환합니다: 종료 상태 표시는 16비트 숫자인데, 하위 바이트가 프로세스를 죽인 시그널 번호이고, 상위 바이트가 종료 상태(시그널 번호가 0이면)입니다; 코어 파일이 생성되면 하위 바이트의 상위 비트가 설정됩니다.

If there are no children that could be waited for, ChildProcessError is raised.

waitstatus_to_exitcode()를 사용하여 종료 상태를 종료 코드로 변환할 수 있습니다.

Availability: Unix, not Emscripten, not WASI.

더 보기

The other wait*() functions documented below can be used to wait for the completion of a specific child process and have more options. waitpid() is the only one also available on Windows.

os.waitid(idtype, id, options, /)

Wait for the completion of a child process.

idtype can be P_PID, P_PGID, P_ALL, or (on Linux) P_PIDFD. The interpretation of id depends on it; see their individual descriptions.

options is an OR combination of flags. At least one of WEXITED, WSTOPPED or WCONTINUED is required; WNOHANG and WNOWAIT are additional optional flags.

The return value is an object representing the data contained in the siginfo_t structure with the following attributes:

  • si_pid (process ID)

  • si_uid (real user ID of the child)

  • si_signo (always SIGCHLD)

  • si_status (the exit status or signal number, depending on si_code)

  • si_code (see CLD_EXITED for possible values)

If WNOHANG is specified and there are no matching children in the requested state, None is returned. Otherwise, if there are no matching children that could be waited for, ChildProcessError is raised.

Availability: Unix, not Emscripten, not WASI.

참고

This function is not available on macOS.

버전 3.3에 추가.

os.waitpid(pid, options, /)

이 함수의 세부 사항은 유닉스 및 윈도우에서 다릅니다.

유닉스에서: 프로세스 ID pid에 의해 주어진 자식 프로세스의 완료를 기다리고, 프로세스 ID와 종료 상태 표시(wait()처럼 인코딩됨)를 포함하는 튜플을 반환합니다. 호출의 의미는 정수 options 의 값에 영향을 받는데, 일반 작업의 경우 0 이어야 합니다.

pid0보다 크면, waitpid()는 해당 프로세스에 대한 상태 정보를 요청합니다. pid0이면, 현재 프로세스의 프로세스 그룹에 있는 모든 자식의 상태를 요청합니다. pid-1이면, 현재 프로세스의 모든 자식의 상태를 요청합니다. pid-1보다 작으면, 프로세스 그룹 -pid(pid 의 절댓값)에 있는 모든 프로세스의 상태를 요청합니다.

options is an OR combination of flags. If it contains WNOHANG and there are no matching children in the requested state, (0, 0) is returned. Otherwise, if there are no matching children that could be waited for, ChildProcessError is raised. Other options that can be used are WUNTRACED and WCONTINUED.

윈도우에서: 프로세스 핸들 pid로 지정된 프로세스가 완료될 때까지 기다리고, pid와 종료 상태를 8비트 왼쪽으로 시프트 한 값을 포함하는 튜플을 반환합니다 (시프팅이 함수를 더 이식성 있게 만듭니다). 0보다 작거나 같은 pid 는 윈도우에서 특별한 의미가 없고 예외가 발생합니다. 정수 options 의 값은 아무 효과가 없습니다. pid 는 id가 알려진 모든 프로세스를 가리킬 수 있습니다, 반드시 자식 프로세스일 필요는 없습니다. P_NOWAIT로 호출된 spawn* 함수는 적절한 프로세스 핸들을 반환합니다.

waitstatus_to_exitcode()를 사용하여 종료 상태를 종료 코드로 변환할 수 있습니다.

Availability: Unix, Windows, not Emscripten, not WASI.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 함수는 이제 InterruptedError 예외를 일으키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475를 참조하세요).

os.wait3(options)

Similar to waitpid(), except no process id argument is given and a 3-element tuple containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource.getrusage() for details on resource usage information. The options argument is the same as that provided to waitpid() and wait4().

waitstatus_to_exitcode()를 사용하여 종료 상태를 종료 코드로 변환할 수 있습니다.

Availability: Unix, not Emscripten, not WASI.

os.wait4(pid, options)

Similar to waitpid(), except a 3-element tuple, containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource.getrusage() for details on resource usage information. The arguments to wait4() are the same as those provided to waitpid().

waitstatus_to_exitcode()를 사용하여 종료 상태를 종료 코드로 변환할 수 있습니다.

Availability: Unix, not Emscripten, not WASI.

os.P_PID
os.P_PGID
os.P_ALL
os.P_PIDFD

These are the possible values for idtype in waitid(). They affect how id is interpreted:

  • P_PID - wait for the child whose PID is id.

  • P_PGID - wait for any child whose progress group ID is id.

  • P_ALL - wait for any child; id is ignored.

  • P_PIDFD - wait for the child identified by the file descriptor id (a process file descriptor created with pidfd_open()).

Availability: Unix, not Emscripten, not WASI.

참고

P_PIDFD is only available on Linux >= 5.4.

버전 3.3에 추가.

버전 3.9에 추가: The P_PIDFD constant.

os.WCONTINUED

This options flag for waitpid(), wait3(), wait4(), and waitid() causes child processes to be reported if they have been continued from a job control stop since they were last reported.

Availability: Unix, not Emscripten, not WASI.

os.WEXITED

This options flag for waitid() causes child processes that have terminated to be reported.

The other wait* functions always report children that have terminated, so this option is not available for them.

Availability: Unix, not Emscripten, not WASI.

버전 3.3에 추가.

os.WSTOPPED

This options flag for waitid() causes child processes that have been stopped by the delivery of a signal to be reported.

This option is not available for the other wait* functions.

Availability: Unix, not Emscripten, not WASI.

버전 3.3에 추가.

os.WUNTRACED

This options flag for waitpid(), wait3(), and wait4() causes child processes to also be reported if they have been stopped but their current state has not been reported since they were stopped.

This option is not available for waitid().

Availability: Unix, not Emscripten, not WASI.

os.WNOHANG

This options flag causes waitpid(), wait3(), wait4(), and waitid() to return right away if no child process status is available immediately.

Availability: Unix, not Emscripten, not WASI.

os.WNOWAIT

This options flag causes waitid() to leave the child in a waitable state, so that a later wait*() call can be used to retrieve the child status information again.

This option is not available for the other wait* functions.

Availability: Unix, not Emscripten, not WASI.

os.CLD_EXITED
os.CLD_KILLED
os.CLD_DUMPED
os.CLD_TRAPPED
os.CLD_STOPPED
os.CLD_CONTINUED

These are the possible values for si_code in the result returned by waitid().

Availability: Unix, not Emscripten, not WASI.

버전 3.3에 추가.

버전 3.9에서 변경: CLD_KILLEDCLD_STOPPED 값을 추가했습니다.

os.waitstatus_to_exitcode(status)

대기 상태(wait status)를 종료 코드로 변환합니다.

유닉스에서:

  • 프로세스가 정상적으로 종료되면 (WIFEXITED(status)가 참이면), 프로세스 종료 상태를 반환합니다 (WEXITSTATUS(status)를 반환합니다): 결과는 0보다 크거나 같습니다.

  • 프로세스가 시그널에 의해 종료되면 (WIFSIGNALED(status)가 참이면), -signum을 반환합니다, 여기서 signum은 프로세스를 종료시킨 시그널 번호입니다 (-WTERMSIG(status)를 반환합니다): 결과는 0보다 작습니다.

  • 그렇지 않으면, ValueError를 발생시킵니다.

윈도우에서, 8비트만큼 오른쪽으로 시프트된 status를 반환합니다.

유닉스에서, 프로세스가 추적되고 있거나 waitpid()WUNTRACED 옵션으로 호출되었으면, 호출자는 먼저 WIFSTOPPED(status)가 참인지 확인해야 합니다. WIFSTOPPED(status)가 참이면 이 함수를 호출하면 안 됩니다.

Availability: Unix, Windows, not Emscripten, not WASI.

버전 3.9에 추가.

다음 함수들은 system(), wait() 또는 waitpid()에 의해 반환된 프로세스 상태 코드를 매개 변수로 받아들입니다. 이것들은 프로세스의 처리를 결정하는 데 사용될 수 있습니다.

os.WCOREDUMP(status, /)

프로세스에 대해 코어 덤프가 생성되었으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

이 함수는 WIFSIGNALED()가 참일 때만 사용해야 합니다.

Availability: Unix, not Emscripten, not WASI.

os.WIFCONTINUED(status)

Return True if a stopped child has been resumed by delivery of SIGCONT (if the process has been continued from a job control stop), otherwise return False.

WCONTINUED 옵션을 참조하십시오.

Availability: Unix, not Emscripten, not WASI.

os.WIFSTOPPED(status)

시그널의 전달로 인해 프로세스가 중지되었으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

WIFSTOPPED()WUNTRACED 옵션을 사용하여 waitpid()을 호출했거나 프로세스가 추적되고 있을 때만 True를 반환합니다 (ptrace(2)를 참조하십시오).

Availability: Unix, not Emscripten, not WASI.

os.WIFSIGNALED(status)

시그널로 인해 프로세스가 종료되었으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

Availability: Unix, not Emscripten, not WASI.

os.WIFEXITED(status)

프로세스가 정상 종료했으면 True를 반환합니다, 즉 exit()_exit()를 호출했거나, main()에서 반환하여; 그렇지 않으면 False를 반환합니다.

Availability: Unix, not Emscripten, not WASI.

os.WEXITSTATUS(status)

프로세스 종료 상태를 반환합니다.

이 함수는 WIFEXITED()가 참일 때만 사용해야 합니다.

Availability: Unix, not Emscripten, not WASI.

os.WSTOPSIG(status)

프로세스를 멈추게 한 시그널을 반환합니다.

이 함수는 WIFSTOPPED()가 참일 때만 사용해야 합니다.

Availability: Unix, not Emscripten, not WASI.

os.WTERMSIG(status)

프로세스를 종료시킨 시그널의 번호를 반환합니다.

이 함수는 WIFSIGNALED()가 참일 때만 사용해야 합니다.

Availability: Unix, not Emscripten, not WASI.

스케줄러에 대한 인터페이스

이 함수들은 운영 체제가 프로세스에 CPU 시간을 할당하는 방법을 제어합니다. 일부 유닉스 플랫폼에서만 사용할 수 있습니다. 자세한 내용은 유닉스 매뉴얼 페이지를 참조하십시오.

버전 3.3에 추가.

다음 스케줄 정책은 운영 체제에서 지원하는 경우 공개됩니다.

os.SCHED_OTHER

기본 스케줄 정책.

os.SCHED_BATCH

컴퓨터의 나머지 부분에서 반응성을 유지하려고 하는 CPU 집약적인 프로세스를 위한 스케줄 정책.

os.SCHED_IDLE

매우 낮은 우선순위의 배경 작업에 대한 스케줄 정책.

os.SCHED_SPORADIC

간헐적인 서버 프로그램을 위한 스케줄 정책.

os.SCHED_FIFO

선입 선출 (First In First Out) 스케줄 정책.

os.SCHED_RR

라운드 로빈 스케줄 정책.

os.SCHED_RESET_ON_FORK

이 플래그는 다른 스케줄 정책과 OR 될 수 있습니다. 이 플래그가 설정되어있는 프로세스가 포크 할 때, 자식의 스케줄링 정책 및 우선순위가 기본값으로 재설정됩니다.

class os.sched_param(sched_priority)

이 클래스는 sched_setparam(), sched_setscheduler(), 및 sched_getparam()에서 사용되는 튜닝 가능한 스케줄 파라미터를 나타냅니다. 불변입니다.

현재, 가능한 매개 변수는 하나뿐입니다:

sched_priority

스케줄 정책의 스케줄 우선순위.

os.sched_get_priority_min(policy)

policy의 최소 우선순위 값을 가져옵니다. policy 는 위의 스케줄 정책 상수 중 하나입니다.

os.sched_get_priority_max(policy)

policy의 최대 우선순위 값을 가져옵니다. policy 는 위의 스케줄 정책 상수 중 하나입니다.

os.sched_setscheduler(pid, policy, param, /)

PID가 pid인 프로세스의 스케줄 정책을 설정합니다. pid 가 0이면, 호출하는 프로세스를 의미합니다. policy 는 위의 스케줄 정책 상수 중 하나입니다. paramsched_param 인스턴스입니다.

os.sched_getscheduler(pid, /)

PID가 pid인 프로세스의 스케줄 정책을 반환합니다. pid 가 0이면, 호출하는 프로세스를 의미합니다. 결과는 위의 스케줄 정책 상수 중 하나입니다.

os.sched_setparam(pid, param, /)

Set the scheduling parameters for the process with PID pid. A pid of 0 means the calling process. param is a sched_param instance.

os.sched_getparam(pid, /)

PID가 pid인 프로세스의 스케줄 매개 변수를 sched_param 인스턴스로 반환합니다. pid 가 0이면 호출하는 프로세스를 의미합니다.

os.sched_rr_get_interval(pid, /)

PID가 pid인 프로세스의 라운드 로빈 퀀텀을 초 단위로 반환합니다. pid 가 0이면 호출하는 프로세스를 의미합니다.

os.sched_yield()

자발적으로 CPU를 양도합니다.

os.sched_setaffinity(pid, mask, /)

PID가 pid인 프로세스(또는 0이면 현재 프로세스)를 CPU 집합으로 제한합니다. mask 는 프로세스가 제한되어야 하는 CPU 집합을 나타내는 정수의 이터러블입니다.

os.sched_getaffinity(pid, /)

Return the set of CPUs the process with PID pid is restricted to.

If pid is zero, return the set of CPUs the calling thread of the current process is restricted to.

기타 시스템 정보

os.confstr(name, /)

문자열 값 시스템 구성 값을 반환합니다. name 은 조회할 구성 값을 지정합니다; 정의된 시스템 값의 이름인 문자열일 수 있습니다; 이 이름은 여러 표준(POSIX, 유닉스 95, 유닉스 98 및 기타)에서 지정됩니다. 일부 플랫폼은 추가 이름도 정의합니다. 호스트 운영 체제에 알려진 이름은 confstr_names 딕셔너리의 키로 제공됩니다. 해당 매핑에 포함되지 않은 구성 변수를 위해, name에 정수를 전달하는 것도 허용됩니다.

name 으로 지정된 구성 값이 정의되어 있지 않으면, None이 반환됩니다.

name 이 문자열이고 알 수 없으면, ValueError가 발생합니다. name에 대한 특정 값이 호스트 시스템에서 지원되지 않으면, confstr_names에 포함되어 있어도, 에러 번호 errno.EINVALOSError가 발생합니다.

가용성: 유닉스.

os.confstr_names

confstr()에서 허용하는 이름을 호스트 운영 체제가 해당 이름에 대해 정의한 정숫값으로 매핑하는 딕셔너리입니다. 이것은 시스템에 알려진 이름 집합을 판별하는 데 사용될 수 있습니다.

가용성: 유닉스.

os.cpu_count()

Return the number of logical CPUs in the system. Returns None if undetermined.

This number is not equivalent to the number of logical CPUs the current process can use. len(os.sched_getaffinity(0)) gets the number of logical CPUs the calling thread of the current process is restricted to

버전 3.4에 추가.

os.getloadavg()

마지막 1, 5, 15분에 걸쳐 평균한 시스템 실행 대기열의 프로세스 수를 반환하거나, 로드 평균을 얻을 수 없으면, OSError를 발생시킵니다.

가용성: 유닉스.

os.sysconf(name, /)

정숫값 시스템 구성 값을 반환합니다. name 으로 지정된 구성 값이 정의되어 있지 않으면, -1이 반환됩니다. confstr()name 매개 변수에 관한 주석은 여기에도 적용됩니다; 알려진 이름에 대한 정보를 제공하는 딕셔너리는 sysconf_names에 의해 제공됩니다.

가용성: 유닉스.

os.sysconf_names

sysconf()에서 허용하는 이름을 호스트 운영 체제가 해당 이름에 대해 정의한 정숫값으로 매핑하는 딕셔너리입니다. 이것은 시스템에 알려진 이름 집합을 판별하는 데 사용될 수 있습니다.

가용성: 유닉스.

버전 3.11에서 변경: Add 'SC_MINSIGSTKSZ' name.

다음 데이터값들은 경로 조작 연산을 지원하는 데 사용됩니다. 이는 모든 플랫폼에서 정의됩니다.

경로명에 대한 고수준 연산은 os.path 모듈에서 정의됩니다.

os.curdir

현재 디렉터리를 가리키기 위해 운영 체제에서 사용하는 상수 문자열. 이것은 윈도우 및 POSIX의 경우 '.'입니다. os.path를 통해서도 제공됩니다.

os.pardir

부모 디렉터리를 가리키기 위해 운영 체제에서 사용하는 상수 문자열입니다. 이것은 윈도우 및 POSIX의 경우 '..'입니다. os.path를 통해서도 제공됩니다.

os.sep

경로명 구성 요소를 분리하기 위해 운영 체제에서 사용하는 문자. 이것은 POSIX의 경우 '/'이고, 윈도우의 경우 '\\'입니다. 이것을 아는 것만으로는 경로명을 구문 분석하거나 이어붙일 수는 없습니다만 — os.path.split()os.path.join()를 사용하세요 — 가끔 유용합니다. os.path를 통해서도 제공됩니다.

os.altsep

경로명 구성 요소를 분리하기 위해 운영 체제에서 사용하는 대체 문자이거나, 단 하나의 구분 문자만 있는 경우 None입니다. sep가 백 슬래시인 윈도우 시스템에서는 '/'로 설정됩니다. os.path를 통해서도 제공됩니다.

os.extsep

기본 파일명과 확장자를 구분하는 문자; 예를 들어, os.py에서 '.'. os.path를 통해서도 제공됩니다.

os.pathsep

검색 경로 구성 요소(PATH에서와 같이)를 분리하기 위해 운영 체제에서 관습적으로 사용하는 문자, 가령 POSIX의 ':' 또는 윈도우의 ';'. os.path를 통해서도 제공됩니다.

os.defpath

환경에 'PATH' 키가 없을 때, exec*p*spawn*p*에서 사용하는 기본 검색 경로. os.path를 통해서도 제공됩니다.

os.linesep

현재 플랫폼에서 행을 분리(또는 종료)하는 데 사용되는 문자열. 이는 POSIX의 '\n'와 같은 단일 문자이거나, 윈도우의 '\r\n'와 같은 여러 문자일 수 있습니다. 텍스트 모드로 열린(기본값) 파일에 쓸 때 줄 종결자로 os.linesep를 사용하지 마십시오; 대신 모든 플랫폼에서 단일 '\n'를 사용하십시오.

os.devnull

널(null) 장치의 파일 경로. 예를 들어: POSIX의 경우 '/dev/null', 윈도우의 경우 'nul'. os.path를 통해서도 제공됩니다.

os.RTLD_LAZY
os.RTLD_NOW
os.RTLD_GLOBAL
os.RTLD_LOCAL
os.RTLD_NODELETE
os.RTLD_NOLOAD
os.RTLD_DEEPBIND

setdlopenflags()getdlopenflags() 함수에 사용하는 플래그. 각 플래그가 의미하는 바는 유닉스 매뉴얼 페이지 dlopen(3)를 참조하십시오.

버전 3.3에 추가.

난수

os.getrandom(size, flags=0)

최대 size 크기의 난수 바이트열을 업습니다. 이 함수는 요청한 것보다 짧은 바이트열를 반환할 수 있습니다.

이 바이트열은 사용자 공간 난수 발생기를 시드 하거나 암호화 목적으로 사용할 수 있습니다.

getrandom()는 장치 드라이버 및 기타 환경 소음원에서 수집한 엔트로피에 의존합니다. 대량의 데이터를 불필요하게 읽는 것은 /dev/random/dev/urandom 장치의 다른 사용자에게 부정적인 영향을 미칩니다.

The flags argument is a bit mask that can contain zero or more of the following values ORed together: os.GRND_RANDOM and GRND_NONBLOCK.

See also the Linux getrandom() manual page.

Availability: Linux >= 3.17.

버전 3.6에 추가.

os.urandom(size, /)

Return a bytestring of size random bytes suitable for cryptographic use.

이 함수는 OS 종속적인 임의성 소스에서 난수 바이트열을 반환합니다. 반환된 데이터는 암호화 응용에 충분하도록 예측할 수 없어야 하지만, 정확한 품질은 OS 구현에 따라 달라집니다.

리눅스에서, getrandom() 시스템 호출을 사용할 수 있으면, 블로킹 모드로 사용됩니다: 시스템의 urandom 엔트로피 풀이 초기화될 때까지 블록 됩니다 (커널이 128비트의 엔트로피를 수집합니다). 이유는 PEP 524를 참조하십시오. 리눅스에서, getrandom() 함수는 (GRND_NONBLOCK 플래그를 사용하여) 비 블로킹 모드로 난수 바이트열을 얻거나, 시스템 urandom 엔트로피 풀이 초기화될 때까지 폴링 할 수 있습니다.

유닉스류 시스템에서, /dev/urandom 장치에서 난수 바이트열을 읽습니다. /dev/urandom 장치를 사용할 수 없거나 읽을 수 없으면, NotImplementedError 예외가 발생합니다.

On Windows, it will use BCryptGenRandom().

더 보기

secrets 모듈은 고수준 함수를 제공합니다. 플랫폼에서 제공되는 난수 발생기에 대한 사용하기 쉬운 인터페이스는 random.SystemRandom를 참조하십시오.

버전 3.5에서 변경: 리눅스 3.17 및 이후 버전에서, 이제 getrandom() 시스템 호출을 사용할 수 있으면 사용합니다. OpenBSD 5.6 이상에서, C getentropy() 함수가 이제 사용됩니다. 이 함수들은 내부 파일 기술자의 사용을 피합니다.

버전 3.5.2에서 변경: 리눅스에서, getrandom() 시스템 호출이 블록 하면 (urandom 엔트로피 풀이 아직 초기화되지 않았으면), /dev/urandom을 읽는 것으로 대체됩니다.

버전 3.6에서 변경: 리눅스에서, getrandom()은 이제 보안을 강화하기 위해 블로킹 모드로 사용됩니다.

버전 3.11에서 변경: On Windows, BCryptGenRandom() is used instead of CryptGenRandom() which is deprecated.

os.GRND_NONBLOCK

기본적으로, /dev/random에서 읽을 때, getrandom()는 사용할 수 있는 난수 바이트열이 없으면 블록 하고, /dev/urandom에서 읽을 때는, 엔트로피 풀이 아직 초기화되지 않았으면 블록 합니다.

GRND_NONBLOCK 플래그가 설정되면, getrandom()는 이럴 때 블록 하지 않고, 대신 즉시 BlockingIOError를 발생시킵니다.

버전 3.6에 추가.

os.GRND_RANDOM

이 비트가 설정되면, /dev/urandom 풀 대신 /dev/random 풀에서 난수 바이트열을 얻습니다.

버전 3.6에 추가.