os
--- Miscellaneous operating system interfaces¶
Kode sumber: Lib/os.py
Modul ini menyediakan cara portabel menggunakan fungsionalitas yang bergantung pada sistem operasi. Jika Anda hanya ingin membaca atau menulis file, lihat open()
, jika Anda ingin memanipulasi path, lihat modul os.path
, dan jika Anda ingin membaca semua baris di semua file pada baris perintah lihat modul fileinput
. Untuk membuat file dan direktori sementara lihat modul tempfile
, dan untuk penanganan file dan direktori tingkat tinggi lihat modul shutil
.
Catatan tentang ketersediaan fungsi-fungsi tersebut:
The design of all built-in operating system dependent modules of Python is such that as long as the same functionality is available, it uses the same interface; for example, the function
os.stat(path)
returns stat information about path in the same format (which happens to have originated with the POSIX interface).Extensions peculiar to a particular operating system are also available through the
os
module, but using them is of course a threat to portability.All functions accepting path or file names accept both bytes and string objects, and result in an object of the same type, if a path or file name is returned.
On VxWorks, os.popen, os.fork, os.execv and os.spawn*p* are not supported.
On WebAssembly platforms, Android and iOS, large parts of the
os
module are not available or behave differently. APIs related to processes (e.g.fork()
,execve()
) and resources (e.g.nice()
) are not available. Others likegetuid()
andgetpid()
are emulated or stubs. WebAssembly platforms also lack support for signals (e.g.kill()
,wait()
).
Catatan
All functions in this module raise OSError
(or subclasses thereof) in
the case of invalid or inaccessible file names and paths, or other arguments
that have the correct type, but are not accepted by the operating system.
- os.name¶
Назва імпортованого модуля, залежного від операційної системи. Наразі зареєстровано такі назви:
'posix'
,'nt'
,'java'
.Lihat juga
sys.platform
has a finer granularity.os.uname()
gives system-dependent version information.Модуль
platform
забезпечує детальну перевірку ідентичності системи.
Nama Berkas, Argumen Command Line, dan Variabel Lingkungan¶
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
.
Berubah pada versi 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¶
Added in version 3.7: Lihat PEP 540 untuk lebih detail.
The Python UTF-8 Mode ignores the locale encoding and forces the usage of the UTF-8 encoding:
Use UTF-8 as the filesystem encoding.
sys.getfilesystemencoding()
returns'utf-8'
.locale.getpreferredencoding()
returns'utf-8'
(the do_setlocale argument has no effect).sys.stdin
,sys.stdout
, andsys.stderr
all use UTF-8 as their text encoding, with thesurrogateescape
error handler being enabled forsys.stdin
andsys.stdout
(sys.stderr
continues to usebackslashreplace
as it does in the default locale-aware mode)On Unix,
os.device_encoding()
returns'utf-8'
rather than the device 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()
andos.fsencode()
use the UTF-8 encoding.open()
,io.open()
, andcodecs.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.
Lihat juga
- PEP 686
Python 3.15 will make Python UTF-8 Mode default.
İşleme Parametreleri¶
Ці функції та елементи даних надають інформацію та діють щодо поточного процесу та користувача.
- os.ctermid()¶
Return the filename corresponding to the controlling terminal of the process.
Availability: Unix, 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 togetenv("HOME")
in C.Це зіставлення фіксується під час першого імпорту модуля
os
, зазвичай під час запуску Python як частина обробкиsite.py
. Зміни в середовищі, внесені після цього часу, не відображаються вos.environ
, за винятком змін, внесених безпосередньо шляхом модифікаціїos.environ
.Це відображення можна використовувати для зміни середовища, а також запиту середовища.
putenv()
буде викликано автоматично, коли відображення буде змінено.On Unix, keys and values use
sys.getfilesystemencoding()
and'surrogateescape'
error handler. Useenvironb
if you would like to use a different encoding.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'
.Catatan
Безпосередній виклик
putenv()
не змінюєos.environ
, тому краще змінитиos.environ
.Catatan
On some platforms, including FreeBSD and macOS, setting
environ
may cause memory leaks. Refer to the system documentation forputenv()
.Ви можете видалити елементи в цьому відображенні, щоб скасувати налаштування змінних середовища.
unsetenv()
буде викликано автоматично, коли елемент буде видалено зos.environ
, а також під час виклику одного з методівpop()
абоclear()
.Berubah pada versi 3.9: Updated to support PEP 584's merge (
|
) and update (|=
) operators.
- os.environb¶
Байтова версія
environ
: об’єкт mapping, де і ключі, і значення є об’єктамиbytes
, що представляють середовище процесу.environ
іenvironb
синхронізуються (модифікаціяenvironb
оновлюєenviron
, і навпаки).environb
is only available ifsupports_bytes_environ
isTrue
.Added in version 3.2.
Berubah pada versi 3.9: Updated to support PEP 584's merge (
|
) and update (|=
) operators.
- os.chdir(path)
- os.fchdir(fd)
- os.getcwd()
Fungsi ini dideskripsikan di Dosyalar ve Dizinler.
- os.fsencode(filename)¶
Encode path-like filename to the filesystem encoding and error handler; return
bytes
unchanged.fsdecode()
is the reverse function.Added in version 3.2.
Berubah pada versi 3.6: Додано підтримку прийому об’єктів, що реалізують інтерфейс
os.PathLike
.
- os.fsdecode(filename)¶
Decode the path-like filename from the filesystem encoding and error handler; return
str
unchanged.fsencode()
is the reverse function.Added in version 3.2.
Berubah pada versi 3.6: Додано підтримку прийому об’єктів, що реалізують інтерфейс
os.PathLike
.
- os.fspath(path)¶
Повертає представлення файлової системи шляху.
Якщо передано
str
абоbytes
, воно повертається без змін. В іншому випадку викликається__fspath__()
і повертається його значення, якщо це об’єктstr
абоbytes
. У всіх інших випадках виникаєTypeError
.Added in version 3.6.
- class os.PathLike¶
An abstract base class for objects representing a file system path, e.g.
pathlib.PurePath
.Added in version 3.6.
- 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()
usesos.environ
, the mapping ofgetenv()
is similarly also captured on import, and the function may not reflect future environment changes.В Unix ключі та значення декодуються за допомогою
sys.getfilesystemencoding()
і'surrogateescape'
обробника помилок. Використовуйтеos.getenvb()
, якщо ви хочете використати інше кодування.Availability: Unix, Windows.
- 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()
usesos.environb
, the mapping ofgetenvb()
is similarly also captured on import, and the function may not reflect future environment changes.getenvb()
is only available ifsupports_bytes_environ
isTrue
.Availability: Unix.
Added in version 3.2.
- os.get_exec_path(env=None)¶
Returns the list of directories that will be searched for a named executable, similar to a shell, when launching a process. env, when specified, should be an environment variable dictionary to lookup the PATH in. By default, when env is
None
,environ
is used.Added in version 3.2.
- os.getegid()¶
Return the effective group id of the current process. This corresponds to the "set id" bit on the file being executed in the current process.
Availability: Unix, not WASI.
- os.geteuid()¶
Повернути ефективний ідентифікатор користувача поточного процесу.
Availability: Unix, not WASI.
- os.getgid()¶
Повертає справжній ідентифікатор групи поточного процесу.
Availability: Unix.
The function is a stub on 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 WASI.
Added in version 3.3.
- os.getgroups()¶
Return list of supplemental group ids associated with the current process.
Availability: Unix, not WASI.
Catatan
On macOS,
getgroups()
behavior differs somewhat from other Unix platforms. If the Python interpreter was built with a deployment target of10.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 tosetgroups()
if suitably privileged. If built with a deployment target greater than10.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 tosetgroups()
, and its length is not limited to 16. The deployment target value,MACOSX_DEPLOYMENT_TARGET
, can be obtained withsysconfig.get_config_var()
.
- os.getlogin()¶
Повертає ім’я користувача, який увійшов у систему на керуючому терміналі процесу. Для більшості цілей корисніше використовувати
getpass.getuser()
, оскільки останній перевіряє змінні середовищаLOGNAME
абоUSERNAME
, щоб дізнатися, хто є користувачем, і повертається доpwd.getpwuid(os.getuid())[0]
, щоб отримати ім’я для входу поточного реального ідентифікатора користувача.Availability: Unix, Windows, not WASI.
- os.getpgid(pid)¶
Повертає ідентифікатор групи процесу з ідентифікатором процесу pid. Якщо pid дорівнює 0, повертається ідентифікатор групи поточного процесу.
Availability: Unix, not WASI.
- os.getpgrp()¶
Повертає ідентифікатор поточної групи процесів.
Availability: Unix, not WASI.
- os.getpid()¶
Zwróci ID aktualnego procesu.
The function is a stub on WASI, see WebAssembly platforms for more information.
- os.getppid()¶
Повертає ідентифікатор батьківського процесу. Коли батьківський процес завершив роботу, в Unix повертається ідентифікатор процесу ініціалізації (1), у Windows це все ще той самий ідентифікатор, який може вже повторно використовуватися іншим процесом.
Availability: Unix, Windows, not WASI.
Berubah pada versi 3.2: Dodane wsparcie dla Windowsa.
- os.getpriority(which, who)¶
Отримати пріоритет планування програми. Значення which є одним із
PRIO_PROCESS
,PRIO_PGRP
абоPRIO_USER
, і who інтерпретується відносно which (ідентифікатор процесу дляPRIO_PROCESS
, ідентифікатор групи процесів дляPRIO_PGRP
та ідентифікатор користувача дляPRIO_USER
). Нульове значення для who позначає (відповідно) викликаючий процес, групу процесів викликаючого процесу або справжній ідентифікатор користувача викликаючого процесу.Availability: Unix, not WASI.
Added in version 3.3.
- os.PRIO_PROCESS¶
- os.PRIO_PGRP¶
- os.PRIO_USER¶
Parameter untuk fungsi
getpriority()
dansetpriority()
.Availability: Unix, not WASI.
Added in version 3.3.
- os.PRIO_DARWIN_THREAD¶
- os.PRIO_DARWIN_PROCESS¶
- os.PRIO_DARWIN_BG¶
- os.PRIO_DARWIN_NONUI¶
Parameter untuk fungsi
getpriority()
dansetpriority()
.Availability: macOS
Added in version 3.12.
- os.getresuid()¶
Return a tuple (ruid, euid, suid) denoting the current process's real, effective, and saved user ids.
Availability: Unix, not WASI.
Added in version 3.2.
- os.getresgid()¶
Return a tuple (rgid, egid, sgid) denoting the current process's real, effective, and saved group ids.
Availability: Unix, not WASI.
Added in version 3.2.
- os.getuid()¶
Return the current process's real user id.
Availability: Unix.
The function is a stub on WASI, see WebAssembly platforms for more information.
- os.initgroups(username, gid, /)¶
Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified group id.
Availability: Unix, not WASI, not Android.
Added in version 3.2.
- os.putenv(key, value, /)¶
Set the environment variable named key to the string value. Such changes to the environment affect subprocesses started with
os.system()
,popen()
orfork()
andexecv()
.Assignments to items in
os.environ
are automatically translated into corresponding calls toputenv()
; however, calls toputenv()
don't updateos.environ
, so it is actually preferable to assign to items ofos.environ
. This also applies togetenv()
andgetenvb()
, which respectively useos.environ
andos.environb
in their implementations.Catatan
On some platforms, including FreeBSD and macOS, setting
environ
may cause memory leaks. Refer to the system documentation forputenv()
.Викликає подію аудиту
os.putenv
з аргументамиkey
,value
.Berubah pada versi 3.9: The function is now always available.
- os.setegid(egid, /)¶
Tetapkan id grup proses efektif saat ini.
Availability: Unix, not WASI, not Android.
- os.seteuid(euid, /)¶
Tetapkan id pengguna efektif proses saat ini.
Availability: Unix, not WASI, not Android.
- os.setgid(gid, /)¶
Tetapkan id grup proses saat ini.
Availability: Unix, not WASI, not Android.
- os.setgroups(groups, /)¶
Set the list of supplemental group ids associated with the current process to groups. groups must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser.
Availability: Unix, not WASI.
Catatan
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.
Added in version 3.12.
Lihat juga
The
unshare()
function.
- os.setpgrp()¶
Call the system call
setpgrp()
orsetpgrp(0, 0)
depending on which version is implemented (if any). See the Unix manual for the semantics.Availability: Unix, 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 WASI.
- os.setpriority(which, who, priority)¶
Встановити пріоритет планування програми. Значення which є одним із
PRIO_PROCESS
,PRIO_PGRP
абоPRIO_USER
і who інтерпретується відносно which (ідентифікатор процесу дляPRIO_PROCESS
, ідентифікатор групи процесів дляPRIO_PGRP
та ідентифікатор користувача дляPRIO_USER
). Нульове значення для who позначає (відповідно) викликаючий процес, групу процесів викликаючого процесу або справжній ідентифікатор користувача викликаючого процесу. пріоритет — це значення в діапазоні від -20 до 19. Пріоритет за замовчуванням — 0; нижчі пріоритети викликають більш сприятливе планування.Availability: Unix, not WASI.
Added in version 3.3.
- os.setregid(rgid, egid, /)¶
Set the current process's real and effective group ids.
Availability: Unix, not WASI, not Android.
- os.setresgid(rgid, egid, sgid, /)¶
Встановіть реальні, ефективні та збережені ідентифікатори груп поточного процесу.
Availability: Unix, not WASI, not Android.
Added in version 3.2.
- os.setresuid(ruid, euid, suid, /)¶
Встановіть справжні, ефективні та збережені ідентифікатори користувачів поточного процесу.
Availability: Unix, not WASI, not Android.
Added in version 3.2.
- os.setreuid(ruid, euid, /)¶
Встановіть справжні та ефективні ідентифікатори користувачів поточного процесу.
Availability: Unix, not WASI, not Android.
- os.getsid(pid, /)¶
Call the system call
getsid()
. See the Unix manual for the semantics.Availability: Unix, not WASI.
- os.setsid()¶
Call the system call
setsid()
. See the Unix manual for the semantics.Availability: Unix, not WASI.
- os.setuid(uid, /)¶
Tetapkan id pengguna proses saat ini.
Availability: Unix, not WASI, not Android.
- os.strerror(code, /)¶
Return the error message corresponding to the error code in code. On platforms where
strerror()
returnsNULL
when given an unknown error number,ValueError
is raised.
- os.supports_bytes_environ¶
True
if the native OS type of the environment is bytes (eg.False
on Windows).Added in version 3.2.
- os.umask(mask, /)¶
Установіть поточну цифрову umask і поверніть попередню umask.
The function is a stub on WASI, see WebAssembly platforms for more information.
- os.uname()¶
Повертає інформацію про поточну операційну систему. Значення, що повертається, є об’єктом із п’ятьма атрибутами:
sysname
- nama sistem operasinodename
- name of machine on network (implementation-defined)release
- rilis sistem operasiversion
- versi sistem operasimachine
- pengidentifikasi perangkat keras
Для зворотної сумісності цей об’єкт також можна ітерувати, ведучи себе як п’ять кортежів, що містять
sysname
,nodename
,release
,version
іmachine
в такому порядку.Some systems truncate
nodename
to 8 characters or to the leading component; a better way to get the hostname issocket.gethostname()
or evensocket.gethostbyaddr(socket.gethostname())
.On macOS, iOS and Android, this returns the kernel name and version (i.e.,
'Darwin'
on macOS and iOS;'Linux'
on Android).platform.uname()
can be used to get the user-facing operating system name and version on iOS and Android.Availability: Unix.
Berubah pada versi 3.3: Return type changed from a tuple to a tuple-like object with named attributes.
- os.unsetenv(key, /)¶
Скасувати (видалити) змінну середовища з назвою key. Такі зміни в середовищі впливають на підпроцеси, запущені з
os.system()
,popen()
абоfork()
іexecv()
.Deletion of items in
os.environ
is automatically translated into a corresponding call tounsetenv()
; however, calls tounsetenv()
don't updateos.environ
, so it is actually preferable to delete items ofos.environ
.Викликає подію аудиту
os.unsetenv
з аргументомkey
.Berubah pada versi 3.9: Fonksiyon artık daima mevcut ve Windows'ta da mevcuttur.
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.
Added in version 3.12.
Lihat juga
The
setns()
function.
Pembuatan Objek Berkas¶
Ці функції створюють нові файлові об’єкти. (Див. також open()
для відкриття дескрипторів файлів.)
Операції файлового дескриптора¶
These functions operate on I/O streams referenced using file descriptors.
Дескриптори файлів — це малі цілі числа, що відповідають файлу, відкритому поточним процесом. Наприклад, стандартним введенням зазвичай є дескриптор файлу 0, стандартним виводом є 1, а стандартною помилкою є 2. Іншим файлам, відкритим процесом, буде присвоєно 3, 4, 5 і так далі. Назва "файловий дескриптор" трохи оманлива; на платформах Unix на сокети та канали також посилаються дескриптори файлів.
Метод fileno()
можна використовувати для отримання дескриптора файлу, пов’язаного з file object, коли це необхідно. Зауважте, що використання безпосередньо файлового дескриптора обійде методи файлового об’єкта, ігноруючи такі аспекти, як внутрішня буферизація даних.
- os.close(fd)¶
Закрити файловий дескриптор fd.
- 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 to by src and dst must reside in the same filesystem, otherwise an
OSError
is raised witherrno
set toerrno.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.
The return value is the amount of bytes copied. This could be less than the amount requested.
Catatan
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.
Added in version 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.Berubah pada versi 3.10: On Unix, the function now implements the Python UTF-8 Mode.
- os.dup(fd, /)¶
Повертає дублікат файлового дескриптора fd. Новий файловий дескриптор не успадковується.
У Windows під час дублювання стандартного потоку (0: stdin, 1: stdout, 2: stderr) новий дескриптор файлу є inheritable.
Availability: not WASI.
Berubah pada versi 3.4: Новий файловий дескриптор тепер не успадковується.
- os.dup2(fd, fd2, inheritable=True)¶
Дублюйте файловий дескриптор fd до fd2, закриваючи останній, якщо необхідно. Повернути fd2. Новий файловий дескриптор inheritable за замовчуванням або не успадковується, якщо inheritable має значення
False
.Availability: not WASI.
Berubah pada versi 3.4: Додайте необов’язковий параметр inheritable.
Berubah pada versi 3.7: Return fd2 on success. Previously,
None
was always returned.
- os.fchmod(fd, mode)¶
Змініть режим файлу, заданий fd, на числовий режим. Перегляньте документацію для
chmod()
, щоб дізнатися про можливі значення mode. Починаючи з Python 3.3, це еквівалентноos.chmod(fd, mode)
.Raises an auditing event
os.chmod
with argumentspath
,mode
,dir_fd
.Availability: Unix, Windows.
The function is limited on WASI, see WebAssembly platforms for more information.
Berubah pada versi 3.13: Added support on Windows.
- os.fchown(fd, uid, gid)¶
Змініть ідентифікатор власника та групи файлу, наданий fd, на числові uid і gid. Щоб залишити один із ідентифікаторів без змін, встановіть для нього значення -1. Дивіться
chown()
. Починаючи з Python 3.3, це еквівалентноos.chown(fd, uid, gid)
.Викликає подію аудиту
os.chown
з аргументамиpath
,uid
,gid
,dir_fd
.Availability: Unix.
The function is limited on WASI, see WebAssembly platforms for more information.
- os.fdatasync(fd)¶
Примусовий запис файлу з файловим дескриптором fd на диск. Не примусово оновлювати метадані.
Availability: Unix.
Catatan
Ta funkcja nie jest dostępna w macOS.
- os.fpathconf(fd, name, /)¶
Повертає інформацію про конфігурацію системи, що стосується відкритого файлу. name вказує значення конфігурації для отримання; це може бути рядок, який є назвою визначеного системного значення; ці назви вказані в ряді стандартів (POSIX.1, Unix 95, Unix 98 та інші). Деякі платформи також визначають додаткові імена. Імена, відомі головній операційній системі, наведено у словнику
pathconf_names
. Для змінних конфігурації, не включених до цього відображення, також допускається передача цілого числа для name.If name is a string and is not known,
ValueError
is raised. If a specific value for name is not supported by the host system, even if it is included inpathconf_names
, anOSError
is raised witherrno.EINVAL
for the error number.As of Python 3.3, this is equivalent to
os.pathconf(fd, name)
.Availability: Unix.
- os.fstat(fd)¶
Get the status of the file descriptor fd. Return a
stat_result
object.Починаючи з Python 3.3, це еквівалентно
os.stat(fd)
.Lihat juga
Функція
stat()
.
- os.fstatvfs(fd, /)¶
Повертає інформацію про файлову систему, яка містить файл, пов’язаний із файловим дескриптором fd, наприклад
statvfs()
. Починаючи з Python 3.3, це еквівалентноos.statvfs(fd)
.Availability: Unix.
- 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.If you're starting with a buffered Python file object f, first do
f.flush()
, and then doos.fsync(f.fileno())
, to ensure that all internal buffers associated with f are written to disk.Availability: Unix, Windows.
- os.ftruncate(fd, length, /)¶
Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size. As of Python 3.3, this is equivalent to
os.truncate(fd, length)
.Raises an auditing event
os.truncate
with argumentsfd
,length
.Availability: Unix, Windows.
Berubah pada versi 3.5: Added support for Windows
- os.get_blocking(fd, /)¶
Get the blocking mode of the file descriptor:
False
if theO_NONBLOCK
flag is set,True
if the flag is cleared.Дивіться також
set_blocking()
іsocket.socket.setblocking()
.Availability: Unix, Windows.
The function is limited on WASI, see WebAssembly platforms for more information.
On Windows, this function is limited to pipes.
Added in version 3.5.
Berubah pada versi 3.12: Added support for pipes on Windows.
- os.grantpt(fd, /)¶
Grant access to the slave pseudo-terminal device associated with the master pseudo-terminal device to which the file descriptor fd refers. The file descriptor fd is not closed upon failure.
Calls the C standard library function
grantpt()
.Availability: Unix, not WASI.
Added in version 3.13.
- os.isatty(fd, /)¶
Повертає
True
, якщо файловий дескриптор fd відкрито та підключено до tty(-like) пристрою, інакшеFalse
.
- os.lockf(fd, cmd, len, /)¶
Застосуйте, перевірте або видаліть блокування POSIX для відкритого файлового дескриптора. fd — дескриптор відкритого файлу. cmd визначає команду для використання - одну з
F_LOCK
,F_TLOCK
,F_ULOCK
абоF_TEST
. len вказує розділ файлу, який потрібно заблокувати.Викликає подію аудиту
os.lockf
з аргументамиfd
,cmd
,len
.Availability: Unix.
Added in version 3.3.
- os.F_LOCK¶
- os.F_TLOCK¶
- os.F_ULOCK¶
- os.F_TEST¶
Прапорці, які вказують, яку дію виконуватиме
lockf()
.Availability: Unix.
Added in version 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 WASI.
Added in version 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
or0
-- set pos relative to the beginning of the fileSEEK_CUR
or1
-- set pos relative to the current file positionSEEK_END
or2
-- set pos relative to the end of the fileSEEK_HOLE
-- set pos to the next data location, relative to posSEEK_DATA
-- set pos to the next data hole, relative to pos
Berubah pada versi 3.3: Add support for
SEEK_HOLE
andSEEK_DATA
.
- os.SEEK_SET¶
- os.SEEK_CUR¶
- os.SEEK_END¶
Parameters to the
lseek()
function and theseek()
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 theseek()
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.
Catatan
These operations only make sense for filesystems that support them.
Availability: Linux >= 3.1, macOS, Unix
Added in version 3.3.
- os.open(path, flags, mode=0o777, *, dir_fd=None)¶
Open the file path and set various flags according to flags and possibly its mode according to mode. When computing mode, the current umask value is first masked out. Return the file descriptor for the newly opened file. The new file descriptor is non-inheritable.
For a description of the flag and mode values, see the C run-time documentation; flag constants (like
O_RDONLY
andO_WRONLY
) are defined in theos
module. In particular, on Windows addingO_BINARY
is needed to open files in binary mode.Ця функція може підтримувати шляхи відносно дескрипторів каталогу з параметром dir_fd.
Rzuca auditing event
open
z argumentamipath
,mode
,flags
.Berubah pada versi 3.4: Новий файловий дескриптор тепер не успадковується.
Catatan
Ця функція призначена для низькорівневого введення-виведення. Для звичайного використання використовуйте вбудовану функцію
open()
, яка повертає об’єкт file object з методамиread()
іwrite()
(і набагато більше). Щоб обернути файловий дескриптор у файловий об’єкт, використовуйтеfdopen()
.Berubah pada versi 3.3: Додано параметр dir_fd.
Berubah pada versi 3.5: Jika panggilan sistem terganggu dan penangan sinyal tidak menimbulkan pengecualian, fungsi sekarang mencoba ulang panggilan sistem alih-alih menimbulkan pengecualian
InterruptedError
(lihat PEP 475 untuk penjelasannya).Berubah pada versi 3.6: Menerima sebuah path-like object.
The following constants are options for the flags parameter to the
open()
function. They can be combined using the bitwise OR operator
|
. Some of them are not available on all platforms. For descriptions of
their availability and use, consult the open(2) manual page on Unix
or the MSDN on Windows.
- os.O_RDONLY¶
- os.O_WRONLY¶
- os.O_RDWR¶
- os.O_APPEND¶
- os.O_CREAT¶
- os.O_EXCL¶
- os.O_TRUNC¶
Yukarıdaki sabitler Unix ve Windows'ta mevcuttur.
- os.O_DSYNC¶
- os.O_RSYNC¶
- os.O_SYNC¶
- os.O_NDELAY¶
- os.O_NONBLOCK¶
- os.O_NOCTTY¶
- os.O_CLOEXEC¶
Yukarıdaki sabitler yalnız Unix'te mevcuttur.
Berubah pada versi 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¶
Yukarıdaki sabitler yalnız Windows'ta mevcuttur.
- os.O_EVTONLY¶
- os.O_FSYNC¶
- os.O_SYMLINK¶
- os.O_NOFOLLOW_ANY¶
The above constants are only available on macOS.
Berubah pada versi 3.10: Add
O_EVTONLY
,O_FSYNC
,O_SYMLINK
andO_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.
- os.openpty()¶
Відкрийте нову пару псевдотерміналів. Повертає пару файлових дескрипторів
(master, slave)
для pty і tty відповідно. Нові дескриптори файлів не успадковуються. Для (трохи) більш портативного підходу використовуйте модульpty
.Availability: Unix, not WASI.
Berubah pada versi 3.4: Нові файлові дескриптори тепер не успадковуються.
- os.pipe()¶
Створіть трубу. Повертає пару файлових дескрипторів
(r, w)
, які можна використовувати для читання та запису відповідно. Новий файловий дескриптор не успадковується.Availability: Unix, Windows.
Berubah pada versi 3.4: Нові файлові дескриптори тепер не успадковуються.
- os.pipe2(flags, /)¶
Створіть трубу з прапорцями, встановленими атомарно. прапорці можуть бути створені шляхом об’єднання одного або кількох із цих значень
O_NONBLOCK
,O_CLOEXEC
. Повертає пару файлових дескрипторів(r, w)
, які можна використовувати для читання та запису відповідно.Availability: Unix, not WASI.
Added in version 3.3.
- os.posix_fallocate(fd, offset, len, /)¶
Переконується, що для файлу, указаного fd, виділено достатньо місця на диску, починаючи з offset і продовжуючи len байт.
Availability: Unix.
Added in version 3.3.
- os.posix_fadvise(fd, offset, len, advice, /)¶
Announces an intention to access data in a specific pattern thus allowing the kernel to make optimizations. The advice applies to the region of the file specified by fd starting at offset and continuing for len bytes. advice is one of
POSIX_FADV_NORMAL
,POSIX_FADV_SEQUENTIAL
,POSIX_FADV_RANDOM
,POSIX_FADV_NOREUSE
,POSIX_FADV_WILLNEED
orPOSIX_FADV_DONTNEED
.Availability: Unix.
Added in version 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¶
Flags that can be used in advice in
posix_fadvise()
that specify the access pattern that is likely to be used.Availability: Unix.
Added in version 3.3.
- os.pread(fd, n, offset, /)¶
Read at most n bytes from file descriptor fd at a position of offset, leaving the file offset unchanged.
Повертає байтовий рядок, що містить прочитані байти. Якщо досягнуто кінця файлу, на який посилається fd, повертається порожній об’єкт bytes.
Availability: Unix.
Added in version 3.3.
- os.posix_openpt(oflag, /)¶
Open and return a file descriptor for a master pseudo-terminal device.
Calls the C standard library function
posix_openpt()
. The oflag argument is used to set file status flags and file access modes as specified in the manual page ofposix_openpt()
of your system.The returned file descriptor is non-inheritable. If the value
O_CLOEXEC
is available on the system, it is added to oflag.Availability: Unix, not WASI.
Added in version 3.13.
- os.preadv(fd, buffers, offset, flags=0, /)¶
Читання з файлового дескриптора fd у позиції offset у змінні байт-подібні об’єкти buffers, залишаючи зміщення файлу незмінним. Передайте дані в кожен буфер, доки він не заповниться, а потім перейдіть до наступного буфера в послідовності, щоб утримувати решту даних.
Аргумент flags містить порозрядне АБО нуля або більше таких прапорів:
Return the total number of bytes actually read which can be less than the total capacity of all the objects.
The operating system may set a limit (
sysconf()
value'SC_IOV_MAX'
) on the number of buffers that can be used.Combine the functionality of
os.readv()
andos.pread()
.Availability: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.
Using flags requires Linux >= 4.6.
Added in version 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 toerrno.EAGAIN
.Availability: Linux >= 4.14.
Added in version 3.7.
- os.RWF_HIPRI¶
Високий пріоритет читання/запису. Дозволяє файловим системам на основі блоків використовувати опитування пристрою, що забезпечує меншу затримку, але може використовувати додаткові ресурси.
Currently, on Linux, this feature is usable only on a file descriptor opened using the
O_DIRECT
flag.Availability: Linux >= 4.6.
Added in version 3.7.
- os.ptsname(fd, /)¶
Return the name of the slave pseudo-terminal device associated with the master pseudo-terminal device to which the file descriptor fd refers. The file descriptor fd is not closed upon failure.
Calls the reentrant C standard library function
ptsname_r()
if it is available; otherwise, the C standard library functionptsname()
, which is not guaranteed to be thread-safe, is called.Availability: Unix, not WASI.
Added in version 3.13.
- os.pwrite(fd, str, offset, /)¶
Write the bytestring in str to file descriptor fd at position of offset, leaving the file offset unchanged.
Повертає кількість фактично записаних байтів.
Availability: Unix.
Added in version 3.3.
- os.pwritev(fd, buffers, offset, flags=0, /)¶
Write the buffers contents to file descriptor fd at an offset offset, leaving the file offset unchanged. buffers must be a sequence of bytes-like objects. Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.
Аргумент flags містить порозрядне АБО нуля або більше таких прапорів:
Return the total number of bytes actually written.
The operating system may set a limit (
sysconf()
value'SC_IOV_MAX'
) on the number of buffers that can be used.Combine the functionality of
os.writev()
andos.pwrite()
.Availability: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.
Using flags requires Linux >= 4.6.
Added in version 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.
Added in version 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.
Added in version 3.7.
- os.RWF_APPEND¶
Provide a per-write equivalent of the
O_APPEND
os.open()
flag. This flag is meaningful only foros.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.
Added in version 3.10.
- os.read(fd, n, /)¶
Read at most n bytes from file descriptor fd.
Повертає байтовий рядок, що містить прочитані байти. Якщо досягнуто кінця файлу, на який посилається fd, повертається порожній об’єкт bytes.
Catatan
Ця функція призначена для низькорівневого вводу-виводу та має застосовуватися до дескриптора файлу, який повертає
os.open()
абоpipe()
. Щоб прочитати "файловий об’єкт", повернутий вбудованою функцієюopen()
абоpopen()
абоfdopen()
, абоsys.stdin
, використовуйте йогоread()
абоreadline()
методи.Berubah pada versi 3.5: Jika panggilan sistem terganggu dan penangan sinyal tidak menimbulkan pengecualian, fungsi sekarang mencoba ulang panggilan sistem alih-alih menimbulkan pengecualian
InterruptedError
(lihat PEP 475 untuk penjelasannya).
- os.sendfile(out_fd, in_fd, offset, count)¶
- os.sendfile(out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0)
Copy count bytes from file descriptor in_fd to file descriptor out_fd starting at offset. Return the number of bytes sent. When EOF is reached return
0
.Першу нотацію функції підтримують усі платформи, які визначають
sendfile()
.У Linux, якщо offset задано як
None
, байти зчитуються з поточної позиції in_fd, а позиція in_fd оновлюється.Другий випадок можна використовувати в macOS і FreeBSD, де заголовки і кінці є довільними послідовностями буферів, які записуються до і після запису даних з in_fd. Він повертає те саме, що й перший випадок.
On macOS and FreeBSD, a value of
0
for count specifies to send until the end of in_fd is reached.All platforms support sockets as out_fd file descriptor, and some platforms allow other types (e.g. regular file, pipe) as well.
Cross-platform applications should not use headers, trailers and flags arguments.
Availability: Unix, not WASI.
Catatan
Щоб отримати обгортку вищого рівня
sendfile()
, перегляньтеsocket.socket.sendfile()
.Added in version 3.3.
Berubah pada versi 3.9: Параметри out і in перейменовано на out_fd і in_fd.
- os.SF_NODISKIO¶
- os.SF_MNOWAIT¶
- os.SF_SYNC¶
Параметри функції
sendfile()
, якщо реалізація їх підтримує.Availability: Unix, not WASI.
Added in version 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 WASI.
Added in version 3.11.
- os.set_blocking(fd, blocking, /)¶
Встановити режим блокування вказаного файлового дескриптора. Установіть прапорець
O_NONBLOCK
, якщо блокування має значенняFalse
, зніміть прапорець в іншому випадку.Дивіться також
get_blocking()
іsocket.socket.setblocking()
.Availability: Unix, Windows.
The function is limited on WASI, see WebAssembly platforms for more information.
On Windows, this function is limited to pipes.
Added in version 3.5.
Berubah pada versi 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 beNone
. The files pointed to by src and dst must reside in the same filesystem, otherwise anOSError
is raised witherrno
set toerrno.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. The copy is done as if both files are opened as binary.
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
Added in version 3.10.
- os.readv(fd, buffers, /)¶
Read from a file descriptor fd into a number of mutable bytes-like objects buffers. Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.
Return the total number of bytes actually read which can be less than the total capacity of all the objects.
The operating system may set a limit (
sysconf()
value'SC_IOV_MAX'
) on the number of buffers that can be used.Availability: Unix.
Added in version 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, /)¶
Return a string which specifies the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised.
Availability: Unix.
- os.unlockpt(fd, /)¶
Unlock the slave pseudo-terminal device associated with the master pseudo-terminal device to which the file descriptor fd refers. The file descriptor fd is not closed upon failure.
Calls the C standard library function
unlockpt()
.Availability: Unix, not WASI.
Added in version 3.13.
- os.write(fd, str, /)¶
Запишіть байтовий рядок у str до файлового дескриптора fd.
Повертає кількість фактично записаних байтів.
Catatan
This function is intended for low-level I/O and must be applied to a file descriptor as returned by
os.open()
orpipe()
. To write a "file object" returned by the built-in functionopen()
or bypopen()
orfdopen()
, orsys.stdout
orsys.stderr
, use itswrite()
method.Berubah pada versi 3.5: Jika panggilan sistem terganggu dan penangan sinyal tidak menimbulkan pengecualian, fungsi sekarang mencoba ulang panggilan sistem alih-alih menimbulkan pengecualian
InterruptedError
(lihat PEP 475 untuk penjelasannya).
- os.writev(fd, buffers, /)¶
Write the contents of buffers to file descriptor fd. buffers must be a sequence of bytes-like objects. Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.
Returns the total number of bytes actually written.
The operating system may set a limit (
sysconf()
value'SC_IOV_MAX'
) on the number of buffers that can be used.Availability: Unix.
Added in version 3.3.
Запит розміру терміналу¶
Added in version 3.3.
- os.get_terminal_size(fd=STDOUT_FILENO, /)¶
Return the size of the terminal window as
(columns, lines)
, tuple of typeterminal_size
.Додатковий аргумент
fd
(за замовчуваннямSTDOUT_FILENO
або стандартний вивід) визначає, який дескриптор файлу слід запитувати.Якщо дескриптор файлу не підключено до терміналу, виникає
OSError
.shutil.get_terminal_size()
— це функція високого рівня, яка зазвичай повинна використовуватися,os.get_terminal_size
— це реалізація низького рівня.Availability: Unix, Windows.
Inheritance of File Descriptors¶
Added in version 3.4.
A file descriptor has an "inheritable" flag which indicates if the file descriptor can be inherited by child processes. Since Python 3.4, file descriptors created by Python are non-inheritable by default.
В UNIX неуспадковані файлові дескриптори закриваються в дочірніх процесах під час виконання нової програми, інші файлові дескриптори успадковуються.
У Windows неуспадковані дескриптори та дескриптори файлів закриті в дочірніх процесах, за винятком стандартних потоків (дескриптори файлів 0, 1 і 2: stdin, stdout і stderr), які завжди успадковуються. За допомогою функцій spawn*
успадковуються всі успадковані маркери та всі успадковані дескриптори файлів. За допомогою модуля subprocess
усі файлові дескриптори, крім стандартних потоків, закриваються, а успадковані дескриптори успадковуються, лише якщо параметр close_fds має значення False
.
On WebAssembly platforms, the file descriptor cannot be modified.
- os.get_inheritable(fd, /)¶
Get the "inheritable" flag of the specified file descriptor (a boolean).
- os.set_inheritable(fd, inheritable, /)¶
Set the "inheritable" flag of the specified file descriptor.
- os.get_handle_inheritable(handle, /)¶
Отримайте прапор "успадкований" зазначеного маркера (логічне значення).
Availability: Windows.
- os.set_handle_inheritable(handle, inheritable, /)¶
Встановіть прапорець "успадкований" для вказаного маркера.
Availability: Windows.
Dosyalar ve Dizinler¶
На деяких платформах Unix багато з цих функцій підтримують одну або кілька таких функцій:
зазначення дескриптора файлу: Зазвичай аргумент path, який надається функціям у модулі
os
, має бути рядком, що вказує шлях до файлу. Однак деякі функції тепер альтернативно приймають дескриптор відкритого файлу для свого аргументу path. Потім функція працюватиме з файлом, на який посилається дескриптор. (Для систем POSIX Python викличе варіант функції з префіксомf
(наприклад, викликfchdir
замістьchdir
).)Ви можете перевірити, чи можна вказати шлях як дескриптор файлу для певної функції на вашій платформі за допомогою
os.supports_fd
. Якщо ця функція недоступна, її використання призведе до помилкиNotImplementedError
.Якщо функція також підтримує аргументи dir_fd або follow_symlinks, буде помилкою вказати один із них під час надання шляху як дескриптора файлу.
шляхи відносно дескрипторів каталогу: Якщо dir_fd не є
None
, це має бути дескриптор файлу, який посилається на каталог, а шлях для роботи має бути відносним; тоді шлях буде відносним до цього каталогу. Якщо шлях абсолютний, dir_fd ігнорується. (Для систем POSIX Python викличе варіант функції з суфіксомat
і, можливо, з префіксомf
(наприклад, викликfaccessat
замістьaccess
).You can check whether or not dir_fd is supported for a particular function on your platform using
os.supports_dir_fd
. If it's unavailable, using it will raise aNotImplementedError
.
not following symlinks: If follow_symlinks is
False
, and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself rather than the file pointed to by the link. (For POSIX systems, Python will call thel...
variant of the function.)Ви можете перевірити, чи підтримується follow_symlinks для певної функції на вашій платформі, використовуючи
os.supports_follow_symlinks
. Якщо він недоступний, його використання викличеNotImplementedError
.
- os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)¶
Використовуйте справжній uid/gid, щоб перевірити доступ до шляху. Зауважте, що більшість операцій використовуватиме ефективний uid/gid, тому цю підпрограму можна використовувати в середовищі suid/sgid, щоб перевірити, чи має користувач, який викликає, вказаний доступ до path. режим має бути
F_OK
, щоб перевірити існування шляху, або він може бути включним АБО одного чи кількохR_OK
,W_OK
іX_OK
, щоб перевірити дозволи. ПовертаєTrue
, якщо доступ дозволено,False
, якщо ні. Додаткову інформацію див. на сторінці довідки Unix access(2).This function can support specifying paths relative to directory descriptors and not following symlinks.
If effective_ids is
True
,access()
will perform its access checks using the effective uid/gid instead of the real uid/gid. effective_ids may not be supported on your platform; you can check whether or not it is available usingos.supports_effective_ids
. If it is unavailable, using it will raise aNotImplementedError
.Catatan
Використовуючи
access()
, щоб перевірити, чи має користувач право, наприклад, відкрити файл перед тим, як це зробити за допомогоюopen()
створює діру в безпеці, тому що користувач може використати короткий проміжок часу між перевіркою та відкриттям файлу, щоб маніпулювати ним. Бажано використовувати техніку EAFP. Наприклад:if os.access("myfile", os.R_OK): with open("myfile") as fp: return fp.read() return "some default data"
is better written as:
try: fp = open("myfile") except PermissionError: return "some default data" else: with fp: return fp.read()
Catatan
I/O operations may fail even when
access()
indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.Berubah pada versi 3.3: Added the dir_fd, effective_ids, and follow_symlinks parameters.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.F_OK¶
- os.R_OK¶
- os.W_OK¶
- os.X_OK¶
Значення, які потрібно передавати як параметр mode
access()
, щоб перевірити наявність, читабельність, запис і можливість виконання path відповідно.
- os.chdir(path)¶
Змініть поточний робочий каталог на шлях.
Ця функція може підтримувати зазначення файлового дескриптора. Дескриптор має посилатися на відкритий каталог, а не на відкритий файл.
This function can raise
OSError
and subclasses such asFileNotFoundError
,PermissionError
, andNotADirectoryError
.Викликає подію аудиту
os.chdir
з аргументомpath
.Berubah pada versi 3.3: Added support for specifying path as a file descriptor on some platforms.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.chflags(path, flags, *, follow_symlinks=True)¶
Встановіть прапорці шляху на числові прапорці. flags може приймати комбінацію (порозрядне АБО) таких значень (як визначено в модулі
stat
):This function can support not following symlinks.
Викликає подію аудиту
os.chflags
з аргументамиpath
,flags
.Availability: Unix, not WASI.
Berubah pada versi 3.3: Added the follow_symlinks parameter.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)¶
Змініть режим шляху на числовий режим. mode може приймати одне з наступних значень (як визначено в модулі
stat
) або їх комбінації порозрядними АБО:Ця функція може підтримувати зазначення дескриптора файлу, шляхи відносно дескрипторів каталогу та неперехід за символічними посиланнями.
Catatan
Although Windows supports
chmod()
, you can only set the file's read-only flag with it (via thestat.S_IWRITE
andstat.S_IREAD
constants or a corresponding integer value). All other bits are ignored. The default value of follow_symlinks isFalse
on Windows.The function is limited on WASI, see WebAssembly platforms for more information.
Raises an auditing event
os.chmod
with argumentspath
,mode
,dir_fd
.Berubah pada versi 3.3: Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments.
Berubah pada versi 3.6: Menerima sebuah path-like object.
Berubah pada versi 3.13: Added support for a file descriptor and the follow_symlinks argument on Windows.
- os.chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)¶
Change the owner and group id of path to the numeric uid and gid. To leave one of the ids unchanged, set it to -1.
Ця функція може підтримувати зазначення дескриптора файлу, шляхи відносно дескрипторів каталогу та неперехід за символічними посиланнями.
Перегляньте
shutil.chown()
для функції вищого рівня, яка приймає імена на додаток до числових ідентифікаторів.Викликає подію аудиту
os.chown
з аргументамиpath
,uid
,gid
,dir_fd
.Availability: Unix.
The function is limited on WASI, see WebAssembly platforms for more information.
Berubah pada versi 3.3: Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments.
Berubah pada versi 3.6: Підтримує path-like object.
- os.chroot(path)¶
Change the root directory of the current process to path.
Availability: Unix, not WASI, not Android.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.fchdir(fd)¶
Change the current working directory to the directory represented by the file descriptor fd. The descriptor must refer to an opened directory, not an open file. As of Python 3.3, this is equivalent to
os.chdir(fd)
.Викликає подію аудиту
os.chdir
з аргументомpath
.Availability: Unix.
- os.getcwd()¶
Return a string representing the current working directory.
- os.getcwdb()¶
Повертає байтовий рядок, що представляє поточний робочий каталог.
Berubah pada versi 3.8: Функція тепер використовує кодування UTF-8 у Windows, а не кодову сторінку ANSI: див. PEP 529 для обґрунтування. Ця функція більше не підтримується в Windows.
- os.lchflags(path, flags)¶
Set the flags of path to the numeric flags, like
chflags()
, but do not follow symbolic links. As of Python 3.3, this is equivalent toos.chflags(path, flags, follow_symlinks=False)
.Викликає подію аудиту
os.chflags
з аргументамиpath
,flags
.Availability: Unix, not WASI.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.lchmod(path, mode)¶
Change the mode of path to the numeric mode. If path is a symlink, this affects the symlink rather than the target. See the docs for
chmod()
for possible values of mode. As of Python 3.3, this is equivalent toos.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.Raises an auditing event
os.chmod
with argumentspath
,mode
,dir_fd
.Availability: Unix, Windows, not Linux, FreeBSD >= 1.3, NetBSD >= 1.3, not OpenBSD
Berubah pada versi 3.6: Menerima sebuah path-like object.
Berubah pada versi 3.13: Added support on Windows.
- os.lchown(path, uid, gid)¶
Змініть власника та ідентифікатор групи path на числові uid і gid. Ця функція не переходитиме за символічними посиланнями. Починаючи з Python 3.3, це еквівалентно
os.chown(path, uid, gid, follow_symlinks=False)
.Викликає подію аудиту
os.chown
з аргументамиpath
,uid
,gid
,dir_fd
.Availability: Unix.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)¶
Створіть жорстке посилання на src під назвою dst.
This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors, and not following symlinks.
Raises an auditing event
os.link
with argumentssrc
,dst
,src_dir_fd
,dst_dir_fd
.Availability: Unix, Windows.
Berubah pada versi 3.2: Dodano wsparcie dla WIndowsa.
Berubah pada versi 3.3: Added the src_dir_fd, dst_dir_fd, and follow_symlinks parameters.
Berubah pada versi 3.6: Приймає path-like object для src і dst.
- os.listdir(path='.')¶
Повертає список, що містить імена записів у каталозі, заданому шляхом. Список розташований у довільному порядку й не містить спеціальних записів
'.''
і'..''
, навіть якщо вони присутні в каталозі. Якщо файл видалено з каталогу або додано до нього під час виклику цієї функції, не вказано, чи буде включено ім’я цього файлу.path may be a path-like object. If path is of type
bytes
(directly or indirectly through thePathLike
interface), the filenames returned will also be of typebytes
; in all other circumstances, they will be of typestr
.This function can also support specifying a file descriptor; the file descriptor must refer to a directory.
Викликає подію аудиту
os.listdir
з аргументомpath
.Catatan
To encode
str
filenames tobytes
, usefsencode()
.Lihat juga
Функція
scandir()
повертає записи каталогу разом із інформацією про атрибути файлів, забезпечуючи кращу продуктивність у багатьох поширених випадках використання.Berubah pada versi 3.2: Параметр path став необов'язковим.
Berubah pada versi 3.3: Added support for specifying path as an open file descriptor.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- 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
Added in version 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 argumentvolume
.Availability: Windows
Added in version 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 usingos.listmounts()
.May raise
OSError
if an error occurs collecting the volumes.Raises an auditing event
os.listvolumes
with no arguments.Availability: Windows
Added in version 3.12.
- os.lstat(path, *, dir_fd=None)¶
Perform the equivalent of an
lstat()
system call on the given path. Similar tostat()
, but does not follow symbolic links. Return astat_result
object.On platforms that do not support symbolic links, this is an alias for
stat()
.Починаючи з Python 3.3, це еквівалентно
os.stat(path, dir_fd=dir_fd, follow_symlinks=False)
.Ця функція також може підтримувати шляхи відносно дескрипторів каталогу.
Lihat juga
Функція
stat()
.Berubah pada versi 3.2: Windows 6.0 (Vista) sembolik bağlantıları için destek eklendi.
Berubah pada versi 3.3: Додано параметр dir_fd.
Berubah pada versi 3.6: Menerima sebuah path-like object.
Berubah pada versi 3.8: On Windows, now opens reparse points that represent another path (name surrogates), including symbolic links and directory junctions. Other kinds of reparse points are resolved by the operating system as for
stat()
.
- os.mkdir(path, mode=0o777, *, dir_fd=None)¶
Створіть каталог під назвою path із числовим режимом mode.
If the directory already exists,
FileExistsError
is raised. If a parent directory in the path does not exist,FileNotFoundError
is raised.У деяких системах режим ігнорується. Там, де воно використовується, поточне значення umask спочатку маскується. Якщо встановлено інші біти, ніж останні 9 (тобто останні 3 цифри вісімкового представлення режиму), їхнє значення залежить від платформи. На деяких платформах вони ігноруються, і вам слід явно викликати
chmod()
, щоб встановити їх.В Windows режим
0o700
специально обрабатывается для применения контроля доступа к новому каталогу, чтобы доступ имели только текущий пользователь и администраторы. Другие значения mode игнорируются.Ця функція також може підтримувати шляхи відносно дескрипторів каталогу.
Також є можливість створювати тимчасові каталоги; подивіться функцію
tempfile.mkdtemp()
модуляtempfile
.Викликає подію аудиту
os.mkdir
з аргументамиpath
,mode
,dir_fd
.Berubah pada versi 3.3: Додано параметр dir_fd.
Berubah pada versi 3.6: Menerima sebuah path-like object.
Berubah pada versi 3.13: Windows now handles a mode of
0o700
.
- 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 invokingmakedirs()
. The file permission bits of existing parent directories are not changed.If exist_ok is
False
(the default), aFileExistsError
is raised if the target directory already exists.Catatan
makedirs()
заплутає, якщо елементи шляху, які потрібно створити, включаютьpardir
(наприклад, ".." у системах UNIX).Ця функція правильно обробляє шляхи UNC.
Викликає подію аудиту
os.mkdir
з аргументамиpath
,mode
,dir_fd
.Berubah pada versi 3.2: Added the exist_ok parameter.
Berubah pada versi 3.4.1: До Python 3.4.1, якщо exist_ok було
True
і каталог існував,makedirs()
все одно викликав помилку, якщо mode не відповідав режиму існуючого каталогу. Оскільки таку поведінку було неможливо реалізувати безпечно, її було видалено в Python 3.4.1. Див. bpo-21082.Berubah pada versi 3.6: Menerima sebuah path-like object.
Berubah pada versi 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)¶
Create a FIFO (a named pipe) named path with numeric mode mode. The current umask value is first masked out from the mode.
Ця функція також може підтримувати шляхи відносно дескрипторів каталогу.
FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with
os.unlink()
). Generally, FIFOs are used as rendezvous between "client" and "server" type processes: the server opens the FIFO for reading, and the client opens it for writing. Note thatmkfifo()
doesn't open the FIFO --- it just creates the rendezvous point.Availability: Unix, not WASI.
Berubah pada versi 3.3: Додано параметр dir_fd.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.mknod(path, mode=0o600, device=0, *, dir_fd=None)¶
Create a filesystem node (file, device special file or named pipe) named path. mode specifies both the permissions to use and the type of node to be created, being combined (bitwise OR) with one of
stat.S_IFREG
,stat.S_IFCHR
,stat.S_IFBLK
, andstat.S_IFIFO
(those constants are available instat
). Forstat.S_IFCHR
andstat.S_IFBLK
, device defines the newly created device special file (probably usingos.makedev()
), otherwise it is ignored.Ця функція також може підтримувати шляхи відносно дескрипторів каталогу.
Availability: Unix, not WASI.
Berubah pada versi 3.3: Додано параметр dir_fd.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.major(device, /)¶
Extract the device major number from a raw device number (usually the
st_dev
orst_rdev
field fromstat
).
- os.minor(device, /)¶
Extract the device minor number from a raw device number (usually the
st_dev
orst_rdev
field fromstat
).
- os.makedev(major, minor, /)¶
Compose a raw device number from the major and minor device numbers.
- os.pathconf(path, name)¶
Повертає інформацію про конфігурацію системи, що стосується названого файлу. name вказує значення конфігурації для отримання; це може бути рядок, який є назвою визначеного системного значення; ці назви вказані в ряді стандартів (POSIX.1, Unix 95, Unix 98 та інші). Деякі платформи також визначають додаткові імена. Імена, відомі головній операційній системі, наведено у словнику
pathconf_names
. Для змінних конфігурації, не включених до цього відображення, також допускається передача цілого числа для name.If name is a string and is not known,
ValueError
is raised. If a specific value for name is not supported by the host system, even if it is included inpathconf_names
, anOSError
is raised witherrno.EINVAL
for the error number.This function can support specifying a file descriptor.
Availability: Unix.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.pathconf_names¶
Словник зіставляє імена, прийняті
pathconf()
іfpathconf()
до цілих значень, визначених для цих імен головною операційною системою. Це можна використовувати для визначення набору імен, відомих системі.Availability: Unix.
- os.readlink(path, *, dir_fd=None)¶
Return a string representing the path to which the symbolic link points. The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using
os.path.join(os.path.dirname(path), result)
.Якщо шлях є рядковим об’єктом (прямо чи опосередковано через інтерфейс
PathLike
), результат також буде рядковим об’єктом, і виклик може викликати UnicodeDecodeError. Якщо шлях є об’єктом bytes (прямим чи опосередкованим), результатом буде об’єкт bytes.Ця функція також може підтримувати шляхи відносно дескрипторів каталогу.
Під час спроби визначити шлях, який може містити посилання, використовуйте
realpath()
для належної обробки рекурсії та відмінностей платформи.Availability: Unix, Windows.
Berubah pada versi 3.2: Windows 6.0 (Vista) sembolik bağlantıları için destek eklendi.
Berubah pada versi 3.3: Додано параметр dir_fd.
Berubah pada versi 3.6: Приймає path-like object в Unix.
Berubah pada versi 3.8: Accepts a path-like object and a bytes object on Windows.
Додано підтримку для з’єднань каталогів і змінено, щоб повертати шлях підстановки (який зазвичай включає префікс
\\?\
), а не необов’язкове поле "назви для друку", яке поверталося раніше.
- os.remove(path, *, dir_fd=None)¶
Remove (delete) the file path. If path is a directory, an
OSError
is raised. Usermdir()
to remove directories. If the file does not exist, aFileNotFoundError
is raised.Ця функція може підтримувати шляхи відносно дескрипторів каталогу.
У Windows спроба видалити файл, який використовується, викликає виняток; в Unix запис каталогу видаляється, але сховище, виділене для файлу, не стає доступним, доки оригінальний файл більше не буде використовуватися.
Ця функція семантично ідентична
unlink()
.Raises an auditing event
os.remove
with argumentspath
,dir_fd
.Berubah pada versi 3.3: Додано параметр dir_fd.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.removedirs(name)¶
Remove directories recursively. Works like
rmdir()
except that, if the leaf directory is successfully removed,removedirs()
tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example,os.removedirs('foo/bar/baz')
will first remove the directory'foo/bar/baz'
, and then remove'foo/bar'
and'foo'
if they are empty. RaisesOSError
if the leaf directory could not be successfully removed.Raises an auditing event
os.remove
with argumentspath
,dir_fd
.Berubah pada versi 3.6: Menerima sebuah path-like object.
- 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. Useshutil.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 aNotADirectoryError
will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, anOSError
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()
.Raises an auditing event
os.rename
with argumentssrc
,dst
,src_dir_fd
,dst_dir_fd
.Berubah pada versi 3.3: Added the src_dir_fd and dst_dir_fd parameters.
Berubah pada versi 3.6: Приймає path-like object для src і dst.
- os.renames(old, new)¶
Функція рекурсивного перейменування каталогу або файлу. Працює як
rename()
, за винятком того, що спочатку намагаються створити будь-які проміжні каталоги, необхідні для того, щоб зробити нове ім’я шляху правильним. Після перейменування каталоги, які відповідають крайнім правим сегментам шляху старої назви, будуть видалені за допомогоюremovedirs()
.Catatan
This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file.
Raises an auditing event
os.rename
with argumentssrc
,dst
,src_dir_fd
,dst_dir_fd
.Berubah pada versi 3.6: Accepts a path-like object for old and new.
- os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)¶
Перейменуйте файл або каталог src на dst. Якщо dst є непорожнім каталогом, буде викликано
OSError
. Якщо dst існує і є файлом, його буде замінено мовчки, якщо користувач має дозвіл. Операція може завершитися помилкою, якщо src і dst знаходяться в різних файлових системах. У разі успіху перейменування буде атомарною операцією (це вимога POSIX).Ця функція може підтримувати вказівку src_dir_fd та/або dst_dir_fd для надання шляхів відносно дескрипторів каталогу.
Raises an auditing event
os.rename
with argumentssrc
,dst
,src_dir_fd
,dst_dir_fd
.Added in version 3.3.
Berubah pada versi 3.6: Приймає path-like object для src і dst.
- os.rmdir(path, *, dir_fd=None)¶
Remove (delete) the directory path. If the directory does not exist or is not empty, a
FileNotFoundError
or anOSError
is raised respectively. In order to remove whole directory trees,shutil.rmtree()
can be used.Ця функція може підтримувати шляхи відносно дескрипторів каталогу.
Raises an auditing event
os.rmdir
with argumentspath
,dir_fd
.Berubah pada versi 3.3: Додано параметр dir_fd.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.scandir(path='.')¶
Повертає ітератор об’єктів
os.DirEntry
, що відповідають записам у каталозі, визначеному path. Записи надаються в довільному порядку, і спеціальні записи'.'
і'..'
не включені. Якщо файл видалено з каталогу або додано до нього після створення ітератора, чи буде включений запис для цього файлу, не визначено.Використання
scandir()
замістьlistdir()
може значно підвищити продуктивність коду, який також потребує інформації про тип файлу чи атрибути файлу, оскільки об’єктиos.DirEntry
надають цю інформацію, якщо операційна система надає під час сканування каталогу. Усі методиos.DirEntry
можуть виконувати системний виклик, алеis_dir()
іis_file()
зазвичай вимагають лише системного виклику для символічних посилань;os.DirEntry.stat()
завжди вимагає системного виклику в Unix, але вимагає лише один для символічних посилань у Windows.path may be a path-like object. If path is of type
bytes
(directly or indirectly through thePathLike
interface), the type of thename
andpath
attributes of eachos.DirEntry
will bebytes
; in all other circumstances, they will be of typestr
.This function can also support specifying a file descriptor; the file descriptor must refer to a directory.
Raises an auditing event
os.scandir
with argumentpath
.The
scandir()
iterator supports the context manager protocol and has the following method:- scandir.close()¶
Close the iterator and free acquired resources.
Це викликається автоматично, коли ітератор вичерпано або зібрано сміття, або коли під час ітерації трапляється помилка. Однак бажано викликати його явно або використовувати оператор
with
.Added in version 3.6.
У наступному прикладі показано просте використання
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)
Catatan
On Unix-based systems,
scandir()
uses the system's opendir() and readdir() functions. On Windows, it uses the Win32 FindFirstFileW and FindNextFileW functions.Added in version 3.5.
Berubah pada versi 3.6: Added support for the context manager protocol and the
close()
method. If ascandir()
iterator is neither exhausted nor explicitly closed aResourceWarning
will be emitted in its destructor.Fungsi yang menerima sebuah path-like object.
Berubah pada versi 3.7: Додано підтримку дескрипторів файлів в Unix.
- class os.DirEntry¶
Object yielded by
scandir()
to expose the file path and other file attributes of a directory entry.scandir()
will provide as much of this information as possible without making additional system calls. When astat()
orlstat()
system call is made, theos.DirEntry
object will cache the result.Екземпляри
os.DirEntry
не призначені для зберігання в довгострокових структурах даних; якщо ви знаєте, що метадані файлу змінилися, або якщо після викликуscandir()
минуло багато часу, викличтеos.stat(entry.path)
, щоб отримати актуальну інформацію.Оскільки методи
os.DirEntry
можуть здійснювати виклики операційної системи, вони також можуть викликатиOSError
. Якщо вам потрібен дуже точний контроль над помилками, ви можете перехопитиOSError
під час виклику одного з методівos.DirEntry
і обробити відповідно.Для безпосереднього використання як path-like object,
os.DirEntry
реалізує інтерфейсPathLike
.Атрибути та методи екземпляра
os.DirEntry
такі:- name¶
Базове ім’я файлу запису відносно аргументу path
scandir()
.Атрибут
name
будеbytes
, якщо аргументscandir()
path має типbytes
таstr
інакше. Використовуйтеfsdecode()
для декодування байтових імен файлів.
- path¶
Повний шлях до запису: еквівалент
os.path.join(scandir_path, entry.name)
, де scandir_path є аргументомscandir()
path. Шлях є абсолютним, лише якщо аргумент pathscandir()
був абсолютним. Якщо аргументscandir()
path був дескриптором файлу, атрибутpath
буде таким самим, як атрибутname
.The
path
attribute will bebytes
if thescandir()
path argument is of typebytes
andstr
otherwise. Usefsdecode()
to decode byte filenames.
- inode()¶
Повертає номер inode запису.
The result is cached on the
os.DirEntry
object. Useos.stat(entry.path, follow_symlinks=False).st_ino
to fetch up-to-date information.On the first, uncached call, a system call is required on Windows but not on Unix.
- is_dir(*, follow_symlinks=True)¶
Return
True
if this entry is a directory or a symbolic link pointing to a directory; returnFalse
if the entry is or points to any other kind of file, or if it doesn't exist anymore.Якщо follow_symlinks має значення
False
, повертаєTrue
, лише якщо цей запис є каталогом (без наступних символічних посилань); повертаєFalse
, якщо запис є файлом будь-якого іншого типу або якщо він більше не існує.The result is cached on the
os.DirEntry
object, with a separate cache for follow_symlinksTrue
andFalse
. Callos.stat()
along withstat.S_ISDIR()
to fetch up-to-date information.On the first, uncached call, no system call is required in most cases. Specifically, for non-symlinks, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return
dirent.d_type == DT_UNKNOWN
. If the entry is a symlink, a system call will be required to follow the symlink unless follow_symlinks isFalse
.This method can raise
OSError
, such asPermissionError
, butFileNotFoundError
is caught and not raised.
- is_file(*, follow_symlinks=True)¶
Return
True
if this entry is a file or a symbolic link pointing to a file; returnFalse
if the entry is or points to a directory or other non-file entry, or if it doesn't exist anymore.Якщо follow_symlinks має значення
False
, повертаєTrue
, лише якщо цей запис є файлом (без наступних символічних посилань); повертаєFalse
, якщо запис є каталогом чи іншим записом, що не є файлом, або якщо він більше не існує.The result is cached on the
os.DirEntry
object. Caching, system calls made, and exceptions raised are as peris_dir()
.
- is_symlink()¶
Return
True
if this entry is a symbolic link (even if broken); returnFalse
if the entry points to a directory or any kind of file, or if it doesn't exist anymore.The result is cached on the
os.DirEntry
object. Callos.path.islink()
to fetch up-to-date information.Під час першого некешованого виклику в більшості випадків системний виклик не потрібен. Зокрема, ані Windows, ані Unix не потребують системного виклику, за винятком певних файлових систем Unix, таких як мережеві файлові системи, які повертають
dirent.d_type == DT_UNKNOWN
.This method can raise
OSError
, such asPermissionError
, butFileNotFoundError
is caught and not raised.
- is_junction()¶
Return
True
if this entry is a junction (even if broken); returnFalse
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. Callos.path.isjunction()
to fetch up-to-date information.Added in version 3.12.
- stat(*, follow_symlinks=True)¶
Return a
stat_result
object for this entry. This method follows symbolic links by default; to stat a symbolic link add thefollow_symlinks=False
argument.On Unix, this method always requires a system call. On Windows, it only requires a system call if follow_symlinks is
True
and the entry is a reparse point (for example, a symbolic link or directory junction).У Windows атрибути
st_ino
,st_dev
іst_nlink
stat_result
завжди встановлюються на нуль. Викличтеos.stat()
, щоб отримати ці атрибути.Результат кешується в об’єкті
os.DirEntry
з окремим кешем для follow_symlinksTrue
іFalse
. Зателефонуйтеos.stat()
, щоб отримати актуальну інформацію.
Note that there is a nice correspondence between several attributes and methods of
os.DirEntry
and ofpathlib.Path
. In particular, thename
attribute has the same meaning, as do theis_dir()
,is_file()
,is_symlink()
,is_junction()
, andstat()
methods.Added in version 3.5.
Berubah pada versi 3.6: Додано підтримку інтерфейсу
PathLike
. Додано підтримку шляхівbytes
у Windows.Berubah pada versi 3.12: The
st_ctime
attribute of a stat result is deprecated on Windows. The file creation time is properly available asst_birthtime
, and in the futurest_ctime
may be changed to return zero or the metadata change time, if available.
- os.stat(path, *, dir_fd=None, follow_symlinks=True)¶
Get the status of a file or a file descriptor. Perform the equivalent of a
stat()
system call on the given path. path may be specified as either a string or bytes -- directly or indirectly through thePathLike
interface -- or as an open file descriptor. Return astat_result
object.Ця функція зазвичай слідує за символічними посиланнями; щоб стати символічним посиланням, додайте аргумент
follow_symlinks=False
або використовуйтеlstat()
.This function can support specifying a file descriptor and not following symlinks.
On Windows, passing
follow_symlinks=False
will disable following all name-surrogate reparse points, which includes symlinks and directory junctions. Other types of reparse points that do not resemble links or that the operating system is unable to follow will be opened directly. When following a chain of multiple links, this may result in the original link being returned instead of the non-link that prevented full traversal. To obtain stat results for the final path in this case, use theos.path.realpath()
function to resolve the path name as far as possible and calllstat()
on the result. This does not apply to dangling symlinks or junction points, which will raise the usual exceptions.Contoh:
>>> 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
Berubah pada versi 3.3: Added the dir_fd and follow_symlinks parameters, specifying a file descriptor instead of a path.
Berubah pada versi 3.6: Menerima sebuah path-like object.
Berubah pada versi 3.8: У Windows усі точки повторного аналізу, які може вирішити операційна система, тепер відстежуються, а передача
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 ofos.stat()
,os.fstat()
andos.lstat()
.Öznitelikler:
- st_mode¶
Öznitelikler:
- st_ino¶
Platform dependent, but if non-zero, uniquely identifies the file for a given value of
st_dev
. Typically:the inode number on Unix,
індекс файлу у Windows
- st_dev¶
Ідентифікатор пристрою, на якому знаходиться цей файл.
- st_nlink¶
Кількість жорстких посилань.
- st_uid¶
User identifier of the file owner.
- st_gid¶
Груповий ідентифікатор власника файлу.
- st_size¶
Size of the file in bytes, if it is a regular file or a symbolic link. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte.
Мітки часу:
- st_atime¶
Time of most recent access expressed in seconds.
- st_mtime¶
Time of most recent content modification expressed in seconds.
- st_ctime¶
Time of most recent metadata change expressed in seconds.
Berubah pada versi 3.12:
st_ctime
is deprecated on Windows. Usest_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¶
Час останнього доступу, виражений у наносекундах як ціле число.
Added in version 3.3.
- st_mtime_ns¶
Time of most recent content modification expressed in nanoseconds as an integer.
Added in version 3.3.
- st_ctime_ns¶
Time of most recent metadata change expressed in nanoseconds as an integer.
Added in version 3.3.
Berubah pada versi 3.12:
st_ctime_ns
is deprecated on Windows. Usest_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
.Berubah pada versi 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
.Added in version 3.12.
Catatan
The exact meaning and resolution of the
st_atime
,st_mtime
,st_ctime
andst_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, andst_atime
has only 1-day resolution. See your operating system documentation for details.Similarly, although
st_atime_ns
,st_mtime_ns
,st_ctime_ns
andst_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 storest_atime
,st_mtime
,st_ctime
andst_birthtime
cannot preserve all of it, and as such will be slightly inexact. If you need the exact timestamps you should always usest_atime_ns
,st_mtime_ns
,st_ctime_ns
andst_birthtime_ns
.On some Unix systems (such as Linux), the following attributes may also be available:
- st_blocks¶
Кількість 512-байтних блоків, виділених для файлу. Це може бути менше, ніж
st_size
/512, якщо файл має отвори.
- st_blksize¶
"Preferred" blocksize for efficient file system I/O. Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.
- st_rdev¶
Type of device if an inode device.
- st_flags¶
Визначені користувачем позначки для файлу.
Diğer Unix sistemlerinde (FreeBSD gibi), aşağıdaki öznitelikler mevcuttur (ancak yalnızca kök bunları kullanmaya çalışırsa doldurulabilir):
- st_gen¶
Номер покоління файлу.
On Solaris and derivatives, the following attributes may also be available:
- st_fstype¶
String that uniquely identifies the type of the filesystem that contains the file.
On macOS systems, the following attributes may also be available:
- st_rsize¶
Реальний розмір файлу.
- st_creator¶
Creator of the file.
- st_type¶
Тип файлу.
У системах Windows також доступні такі атрибути:
- st_file_attributes¶
Windows file attributes:
dwFileAttributes
member of theBY_HANDLE_FILE_INFORMATION
structure returned byGetFileInformationByHandle()
. See theFILE_ATTRIBUTE_* <stat.FILE_ATTRIBUTE_ARCHIVE>
constants in thestat
module.Added in version 3.5.
- st_reparse_tag¶
When
st_file_attributes
has theFILE_ATTRIBUTE_REPARSE_POINT
set, this field contains the tag identifying the type of reparse point. See theIO_REPARSE_TAG_*
constants in thestat
module.
The standard module
stat
defines functions and constants that are useful for extracting information from astat
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 thestat
structure, in the orderst_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, accessingstat_result
as a tuple always returns integers.Berubah pada versi 3.5: Тепер Windows повертає індекс файлу як
st_ino
, якщо він доступний.Berubah pada versi 3.7: Додано член
st_fstype
до Solaris/derivatives.Berubah pada versi 3.8: Added the
st_reparse_tag
member on Windows.Berubah pada versi 3.8: У Windows член
st_mode
тепер ідентифікує спеціальні файли якS_IFCHR
,S_IFIFO
абоS_IFBLK
відповідно.Berubah pada versi 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. Usest_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 asst_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 thestatvfs
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
(оновлювати atime відносно mtime/ctime).This function can support specifying a file descriptor.
Availability: Unix.
Berubah pada versi 3.2: Додано константи
ST_RDONLY
іST_NOSUID
.Berubah pada versi 3.3: Added support for specifying path as an open file descriptor.
Berubah pada versi 3.4:
ST_NODEV
,ST_NOEXEC
,ST_SYNCHRONOUS
,ST_MANDLOCK
,ST_WRITE
,ST_APPEND
,ST_IMMUTABLE
, Додано константиST_NOATIME
,ST_NODIRATIME
іST_RELATIME
.Berubah pada versi 3.6: Menerima sebuah path-like object.
Berubah pada versi 3.7: Added the
f_fsid
attribute.
- os.supports_dir_fd¶
Об’єкт
set
, що вказує, які функції в модуліos
приймають дескриптор відкритого файлу для свого параметра dir_fd. Різні платформи надають різні функції, а основні функції, які Python використовує для реалізації параметра dir_fd, доступні не на всіх платформах, які підтримує Python. Заради узгодженості функції, які можуть підтримувати dir_fd, завжди дозволяють вказати параметр, але створять виняток, якщо функція використовується, коли вона недоступна локально. (ВизначенняNone
для dir_fd завжди підтримується на всіх платформах.)Щоб перевірити, чи певна функція приймає дескриптор відкритого файлу для свого параметра dir_fd, використовуйте оператор
in
наsupports_dir_fd
. Як приклад, цей вираз оцінюється якTrue
, якщоos.stat()
приймає дескриптори відкритих файлів для dir_fd на локальній платформі:os.stat in os.supports_dir_fd
Currently dir_fd parameters only work on Unix platforms; none of them work on Windows.
Added in version 3.3.
- os.supports_effective_ids¶
Об’єкт
set
, що вказує, чи дозволяєos.access()
вказуватиTrue
для свого параметра effective_ids на локальній платформі. (ВказівкаFalse
для effective_ids завжди підтримується на всіх платформах.) Якщо локальна платформа підтримує це, колекція міститимеos.access()
; інакше воно буде порожнім.Цей вираз оцінюється як
True
, якщоos.access()
підтримуєeffective_ids=True
на локальній платформі:os.access in os.supports_effective_ids
Currently effective_ids is only supported on Unix platforms; it does not work on Windows.
Added in version 3.3.
- os.supports_fd¶
A
set
object indicating which functions in theos
module permit specifying their path parameter as an open file descriptor on the local platform. Different platforms provide different features, and the underlying functionality Python uses to accept open file descriptors as path arguments is not available on all platforms Python supports.Щоб визначити, чи дозволяє певна функція вказувати дескриптор відкритого файлу для свого параметра path, використовуйте оператор
in
наsupports_fd
. Як приклад, цей вираз має значенняTrue
, якщоos.chdir()
приймає дескриптори відкритих файлів для path на вашій локальній платформі:os.chdir in os.supports_fd
Added in version 3.3.
- os.supports_follow_symlinks¶
Об’єкт
set
, що вказує, які функції в модуліos
приймаютьFalse
для свого параметра follow_symlinks на локальній платформі. Різні платформи надають різні функції, а основні функції, які Python використовує для реалізації follow_symlinks, доступні не на всіх платформах, які підтримує Python. Заради узгодженості функції, які можуть підтримувати follow_symlinks, завжди дозволяють вказувати параметр, але викидають виняток, якщо функція використовується, коли вона недоступна локально. (ВказівкаTrue
для follow_symlinks завжди підтримується на всіх платформах.)Щоб перевірити, чи певна функція приймає
False
для свого параметра follow_symlinks, використовуйте операторin
уsupports_follow_symlinks
. Як приклад, цей вираз має значенняTrue
, якщо ви можете вказатиfollow_symlinks=False
під час викликуos.stat()
на локальній платформі:os.stat in os.supports_follow_symlinks
Added in version 3.3.
- os.symlink(src, dst, target_is_directory=False, *, dir_fd=None)¶
Create a symbolic link pointing to src named dst.
У Windows символічне посилання представляє або файл, або каталог і не перетворюється на ціль динамічно. Якщо ціль присутня, буде створено відповідний тип символічного посилання. В іншому випадку символічне посилання буде створено як каталог, якщо target_is_directory має значення
True
, або символічне посилання на файл (за замовчуванням), інакше. На платформах, відмінних від Windows, target_is_directory ігнорується.Ця функція може підтримувати шляхи відносно дескрипторів каталогу.
Catatan
On newer versions of Windows 10, unprivileged accounts can create symlinks if Developer Mode is enabled. When Developer Mode is not available/enabled, the SeCreateSymbolicLinkPrivilege privilege is required, or the process must be run as an administrator.
OSError
виникає, коли функцію викликає непривілейований користувач.Raises an auditing event
os.symlink
with argumentssrc
,dst
,dir_fd
.Availability: Unix, Windows.
The function is limited on WASI, see WebAssembly platforms for more information.
Berubah pada versi 3.2: Windows 6.0 (Vista) sembolik bağlantıları için destek eklendi.
Berubah pada versi 3.3: Added the dir_fd parameter, and now allow target_is_directory on non-Windows platforms.
Berubah pada versi 3.6: Приймає path-like object для src і dst.
Berubah pada versi 3.8: Added support for unelevated symlinks on Windows with Developer Mode.
- os.sync()¶
Her şeyi diske yazmaya zorla.
Availability: Unix.
Added in version 3.3.
- os.truncate(path, length)¶
Обріжте файл, що відповідає шляху, щоб його розмір не перевищував length байтів.
This function can support specifying a file descriptor.
Викликає подію аудиту
os.truncate
з аргументамиpath
,length
.Availability: Unix, Windows.
Added in version 3.3.
Berubah pada versi 3.5: Added support for Windows
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.unlink(path, *, dir_fd=None)¶
Remove (delete) the file path. This function is semantically identical to
remove()
; theunlink
name is its traditional Unix name. Please see the documentation forremove()
for further information.Raises an auditing event
os.remove
with argumentspath
,dir_fd
.Berubah pada versi 3.3: Додано параметр dir_fd.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.utime(path, times=None, *, [ns, ]dir_fd=None, follow_symlinks=True)¶
Встановіть час доступу та час зміни файлу, указаного шляхом.
utime()
takes two optional parameters, times and ns. These specify the times set on path and are used as follows:Якщо вказано ns, це має бути 2-кортеж у формі
(atime_ns, mtime_ns)
, де кожен член є int, що виражає наносекунди.If times is not
None
, it must be a 2-tuple of the form(atime, mtime)
where each member is an int or float expressing seconds.Якщо times має значення
None
і ns не вказано, це еквівалентно вказівціns=(atime_ns, mtime_ns)
, де обидва часи є поточним часом.
It is an error to specify tuples for both times and ns.
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; seestat()
. The best way to preserve exact times is to use the st_atime_ns and st_mtime_ns fields from theos.stat()
result object with the ns parameter toutime()
.Ця функція може підтримувати зазначення дескриптора файлу, шляхи відносно дескрипторів каталогу та неперехід за символічними посиланнями.
Raises an auditing event
os.utime
with argumentspath
,times
,ns
,dir_fd
.Berubah pada versi 3.3: Додано підтримку для вказівки шляху як дескриптора відкритого файлу та параметрів dir_fd, follow_symlinks і ns.
Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.walk(top, topdown=True, onerror=None, followlinks=False)¶
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple
(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, doos.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.If optional argument topdown is
True
or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown isFalse
, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.When topdown is
True
, the caller can modify the dirnames list in-place (perhaps usingdel
or slice assignment), andwalk()
will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to informwalk()
about directories the caller creates or renames before it resumeswalk()
again. Modifying dirnames when topdown isFalse
has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.By default, errors from the
scandir()
call are ignored. If optional argument onerror is specified, it should be a function; it will be called with one argument, anOSError
instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as thefilename
attribute of the exception object.За замовчуванням
walk()
не переходитиме до символічних посилань, які переходять до каталогів. Встановіть followlinks наTrue
, щоб відвідувати каталоги, на які вказують символічні посилання, у системах, які їх підтримують.Catatan
Майте на увазі, що встановлення followlinks значення
True
може призвести до нескінченної рекурсії, якщо посилання вказує на батьківський каталог самого себе.walk()
не відстежує каталоги, які він уже відвідав.Catatan
If you pass a relative pathname, don't change the current working directory between resumptions of
walk()
.walk()
never changes the current directory, and assumes that its caller doesn't either.This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn't look under any
__pycache__
subdirectory:import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/xml'): print(root, "consumes", end=" ") print(sum(getsize(join(root, name)) for name in files), end=" ") print("bytes in", len(files), "non-directory files") if '__pycache__' in dirs: dirs.remove('__pycache__') # don't visit __pycache__ directories
In the next example (simple implementation of
shutil.rmtree()
), walking the tree bottom-up is essential,rmdir()
doesn't allow deleting a directory before the directory is empty:# 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)) os.rmdir(top)
Викликає подію аудиту
os.walk
з аргументамиtop
,topdown
,onerror
,followlinks
.Berubah pada versi 3.5: Ця функція тепер викликає
os.scandir()
замістьos.listdir()
, що робить її швидшою завдяки зменшенню кількості викликів доos.stat()
.Berubah pada versi 3.6: Menerima sebuah path-like object.
- os.fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)¶
This behaves exactly like
walk()
, except that it yields a 4-tuple(dirpath, dirnames, filenames, dirfd)
, and it supportsdir_fd
.dirpath, dirnames і filenaname ідентичні виводу
walk()
, а dirfd є дескриптором файлу, який посилається на каталог dirpath.Ця функція завжди підтримує шляхи відносно дескрипторів каталогу і не наступні символічні посилання. Проте зауважте, що, на відміну від інших функцій, значенням за замовчуванням
fwalk()
для follow_symlinks єFalse
.Catatan
Since
fwalk()
yields file descriptors, those are only valid until the next iteration step, so you should duplicate them (e.g. withdup()
) if you want to keep them longer.This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn't look under any
__pycache__
subdirectory:import os for root, dirs, files, rootfd in os.fwalk('python/Lib/xml'): 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 '__pycache__' in dirs: dirs.remove('__pycache__') # don't visit __pycache__ directories
In the next example, walking the tree bottom-up is essential:
rmdir()
doesn't allow deleting a directory before the directory is empty:# 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)
Raises an auditing event
os.fwalk
with argumentstop
,topdown
,onerror
,follow_symlinks
,dir_fd
.Availability: Unix.
Added in version 3.3.
Berubah pada versi 3.6: Menerima sebuah path-like object.
Berubah pada versi 3.7: Додано підтримку шляхів
bytes
.
- os.memfd_create(name[, flags=os.MFD_CLOEXEC])¶
Створіть анонімний файл і поверніть дескриптор файлу, який посилається на нього. flags має бути однією з констант
os.MFD_*
, доступних у системі (або їх побітовою комбінацією АБО). За замовчуванням новий файловий дескриптор є non-inheritable.Ім’я, указане в name, використовується як ім’я файлу та відображатиметься як ціль відповідного символічного посилання в каталозі
/proc/self/fd/
. Ім’я, що відображається, завжди має префіксmemfd:
і служить лише для цілей налагодження. Імена не впливають на поведінку файлового дескриптора, тому кілька файлів можуть мати однакові назви без будь-яких побічних ефектів.Availability: Linux >= 3.17 with glibc >= 2.27.
Added in version 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¶
These flags can be passed to
memfd_create()
.Availability: Linux >= 3.17 with glibc >= 2.27
The
MFD_HUGE*
flags are only available since Linux 4.14.Added in version 3.8.
- os.eventfd(initval[, flags=os.EFD_CLOEXEC])¶
Create and return an event file descriptor. The file descriptors supports raw
read()
andwrite()
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 a 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
, andEFD_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.Contoh:
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
Added in version 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 aneventfd()
.Availability: Linux >= 2.6.27
Added in version 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 aneventfd()
.Availability: Linux >= 2.6.27
Added in version 3.10.
- os.EFD_CLOEXEC¶
Set close-on-exec flag for new
eventfd()
file descriptor.Availability: Linux >= 2.6.27
Added in version 3.10.
- os.EFD_NONBLOCK¶
Set
O_NONBLOCK
status flag for neweventfd()
file descriptor.Availability: Linux >= 2.6.27
Added in version 3.10.
- os.EFD_SEMAPHORE¶
Provide semaphore-like semantics for reads from an
eventfd()
file descriptor. On read the internal counter is decremented by one.Availability: Linux >= 2.6.30
Added in version 3.10.
Timer File Descriptors¶
Added in version 3.13.
These functions provide support for Linux's timer file descriptor API. Naturally, they are all only available on Linux.
- os.timerfd_create(clockid, /, *, flags=0)¶
Create and return a timer file descriptor (timerfd).
The file descriptor returned by
timerfd_create()
supports:The file descriptor's
read()
method can be called with a buffer size of 8. If the timer has already expired one or more times,read()
returns the number of expirations with the host's endianness, which may be converted to anint
byint.from_bytes(x, byteorder=sys.byteorder)
.select()
andpoll()
can be used to wait until timer expires and the file descriptor is readable.clockid must be a valid clock ID, as defined in the
time
module:time.CLOCK_BOOTTIME
(Since Linux 3.15 for timerfd_create)
If clockid is
time.CLOCK_REALTIME
, a settable system-wide real-time clock is used. If system clock is changed, timer setting need to be updated. To cancel timer when system clock is changed, seeTFD_TIMER_CANCEL_ON_SET
.If clockid is
time.CLOCK_MONOTONIC
, a non-settable monotonically increasing clock is used. Even if the system clock is changed, the timer setting will not be affected.If clockid is
time.CLOCK_BOOTTIME
, same astime.CLOCK_MONOTONIC
except it includes any time that the system is suspended.The file descriptor's behaviour can be modified by specifying a flags value. Any of the following variables may used, combined using bitwise OR (the
|
operator):If
TFD_NONBLOCK
is not set as a flag,read()
blocks until the timer expires. If it is set as a flag,read()
doesn't block, but If there hasn't been an expiration since the last call to read,read()
raisesOSError
witherrno
is set toerrno.EAGAIN
.TFD_CLOEXEC
is always set by Python automatically.The file descriptor must be closed with
os.close()
when it is no longer needed, or else the file descriptor will be leaked.Lihat juga
The timerfd_create(2) man page.
Availability: Linux >= 2.6.27 with glibc >= 2.8
Added in version 3.13.
- os.timerfd_settime(fd, /, *, flags=flags, initial=0.0, interval=0.0)¶
Alter a timer file descriptor's internal timer. This function operates the same interval timer as
timerfd_settime_ns()
.fd must be a valid timer file descriptor.
The timer's behaviour can be modified by specifying a flags value. Any of the following variables may used, combined using bitwise OR (the
|
operator):The timer is disabled by setting initial to zero (
0
). If initial is equal to or greater than zero, the timer is enabled. If initial is less than zero, it raises anOSError
exception witherrno
set toerrno.EINVAL
By default the timer will fire when initial seconds have elapsed. (If initial is zero, timer will fire immediately.)
However, if the
TFD_TIMER_ABSTIME
flag is set, the timer will fire when the timer's clock (set by clockid intimerfd_create()
) reaches initial seconds.The timer's interval is set by the interval
float
. If interval is zero, the timer only fires once, on the initial expiration. If interval is greater than zero, the timer fires every time interval seconds have elapsed since the previous expiration. If interval is less than zero, it raisesOSError
witherrno
set toerrno.EINVAL
If the
TFD_TIMER_CANCEL_ON_SET
flag is set along withTFD_TIMER_ABSTIME
and the clock for this timer istime.CLOCK_REALTIME
, the timer is marked as cancelable if the real-time clock is changed discontinuously. Reading the descriptor is aborted with the error ECANCELED.Linux manages system clock as UTC. A daylight-savings time transition is done by changing time offset only and doesn't cause discontinuous system clock change.
Discontinuous system clock change will be caused by the following events:
settimeofday
clock_settime
set the system date and time by
date
command
Return a two-item tuple of (
next_expiration
,interval
) from the previous timer state, before this function executed.Lihat juga
timerfd_create(2), timerfd_settime(2), settimeofday(2), clock_settime(2), and date(1).
Availability: Linux >= 2.6.27 with glibc >= 2.8
Added in version 3.13.
- os.timerfd_settime_ns(fd, /, *, flags=0, initial=0, interval=0)¶
Similar to
timerfd_settime()
, but use time as nanoseconds. This function operates the same interval timer astimerfd_settime()
.Availability: Linux >= 2.6.27 with glibc >= 2.8
Added in version 3.13.
- os.timerfd_gettime(fd, /)¶
Return a two-item tuple of floats (
next_expiration
,interval
).next_expiration
denotes the relative time until next the timer next fires, regardless of if theTFD_TIMER_ABSTIME
flag is set.interval
denotes the timer's interval. If zero, the timer will only fire once, afternext_expiration
seconds have elapsed.Lihat juga
Availability: Linux >= 2.6.27 with glibc >= 2.8
Added in version 3.13.
- os.timerfd_gettime_ns(fd, /)¶
Similar to
timerfd_gettime()
, but return time as nanoseconds.Availability: Linux >= 2.6.27 with glibc >= 2.8
Added in version 3.13.
- os.TFD_NONBLOCK¶
A flag for the
timerfd_create()
function, which sets theO_NONBLOCK
status flag for the new timer file descriptor. IfTFD_NONBLOCK
is not set as a flag,read()
blocks.Availability: Linux >= 2.6.27 with glibc >= 2.8
Added in version 3.13.
- os.TFD_CLOEXEC¶
A flag for the
timerfd_create()
function, IfTFD_CLOEXEC
is set as a flag, set close-on-exec flag for new file descriptor.Availability: Linux >= 2.6.27 with glibc >= 2.8
Added in version 3.13.
- os.TFD_TIMER_ABSTIME¶
A flag for the
timerfd_settime()
andtimerfd_settime_ns()
functions. If this flag is set, initial is interpreted as an absolute value on the timer's clock (in UTC seconds or nanoseconds since the Unix Epoch).Availability: Linux >= 2.6.27 with glibc >= 2.8
Added in version 3.13.
- os.TFD_TIMER_CANCEL_ON_SET¶
A flag for the
timerfd_settime()
andtimerfd_settime_ns()
functions along withTFD_TIMER_ABSTIME
. The timer is cancelled when the time of the underlying clock changes discontinuously.Availability: Linux >= 2.6.27 with glibc >= 2.8
Added in version 3.13.
Linux extended attributes¶
Added in version 3.3.
Bu fonksiyonların hepsi yalnız Linux'ta mevcuttur.
- os.getxattr(path, attribute, *, follow_symlinks=True)¶
Return the value of the extended filesystem attribute attribute for path. attribute can be bytes or str (directly or indirectly through the
PathLike
interface). If it is str, it is encoded with the filesystem encoding.This function can support specifying a file descriptor and not following symlinks.
Raises an auditing event
os.getxattr
with argumentspath
,attribute
.Berubah pada versi 3.6: Приймає path-like object для path і attribute.
- os.listxattr(path=None, *, follow_symlinks=True)¶
Повертає список розширених атрибутів файлової системи за шляхом. Атрибути в списку представлені як рядки, декодовані за допомогою кодування файлової системи. Якщо path має значення
None
,listxattr()
перевірить поточний каталог.This function can support specifying a file descriptor and not following symlinks.
Викликає подію аудиту
os.listxattr
з аргументомpath
.Berubah pada versi 3.6: Menerima sebuah path-like object.
- 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.This function can support specifying a file descriptor and not following symlinks.
Викликає подію аудиту
os.removexattr
з аргументамиpath
,attribute
.Berubah pada versi 3.6: Приймає path-like object для path і attribute.
- 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 beXATTR_REPLACE
orXATTR_CREATE
. IfXATTR_REPLACE
is given and the attribute does not exist,ENODATA
will be raised. IfXATTR_CREATE
is given and the attribute already exists, the attribute will not be created andEEXISTS
will be raised.This function can support specifying a file descriptor and not following symlinks.
Catatan
Помилка у версіях ядра Linux до 2.6.39 спричинила ігнорування аргументу flags у деяких файлових системах.
Raises an auditing event
os.setxattr
with argumentspath
,attribute
,value
,flags
.Berubah pada versi 3.6: Приймає path-like object для path і attribute.
- os.XATTR_SIZE_MAX¶
The maximum size the value of an extended attribute can be. Currently, this is 64 KiB on Linux.
- os.XATTR_CREATE¶
This is a possible value for the flags argument in
setxattr()
. It indicates the operation must create an attribute.
- os.XATTR_REPLACE¶
This is a possible value for the flags argument in
setxattr()
. It indicates the operation must replace an existing attribute.
Process Management¶
These functions may be used to create and manage processes.
Різні функції exec*
приймають список аргументів для нової програми, завантаженої в процес. У кожному випадку перший із цих аргументів передається новій програмі як її власне ім’я, а не як аргумент, який користувач міг ввести в командному рядку. Для програміста на C це argv[0]
, що передається до main()
програми. Наприклад, os.execv('/bin/echo', ['foo', 'bar'])
виведе лише bar
на стандартному виводі; foo
буде проігноровано.
- os.abort()¶
Generate a
SIGABRT
signal to the current process. On Unix, the default behavior is to produce a core dump; on Windows, the process immediately returns an exit code of3
. Be aware that calling this function will not call the Python signal handler registered forSIGABRT
withsignal.signal()
.
- os.add_dll_directory(path)¶
Додайте шлях до шляху пошуку DLL.
Цей шлях пошуку використовується під час вирішення залежностей для імпортованих модулів розширення (сам модуль вирішується за допомогою
sys.path
), а також за допомогоюctypes
.Remove the directory by calling close() on the returned object or using it in a
with
statement.Перегляньте документацію Microsoft, щоб дізнатися більше про те, як завантажуються DLL.
Raises an auditing event
os.add_dll_directory
with argumentpath
.Availability: Windows.
Added in version 3.8: Попередні версії CPython вирішували DLL, використовуючи типову поведінку для поточного процесу. Це призвело до неузгодженості, наприклад лише іноді пошук
PATH
або поточного робочого каталогу, а функції ОС, такі якAddDllDirectory
, не мали ефекту.У версії 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)¶
Усі ці функції виконують нову програму, замінюючи поточний процес; вони не повертаються. В Unix новий виконуваний файл завантажується в поточний процес і матиме той самий ідентифікатор процесу, що й виклик. Помилки повідомлятимуться як винятки
OSError
.Поточний процес негайно замінюється. Відкриті файлові об’єкти та дескриптори не скидаються, тому, якщо у цих відкритих файлах можуть бути буферизовані дані, вам слід очистити їх за допомогою
sys.stdout.flush()
абоos.fsync()
перед викликомexec*
функція.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 theexecl*()
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()
, andexecvpe()
) will use thePATH
environment variable to locate the program file. When the environment is being replaced (using one of theexec*e
variants, discussed in the next paragraph), the new environment is used as the source of thePATH
variable. The other variants,execl()
,execle()
,execv()
, andexecve()
, will not use thePATH
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()
на деяких платформах шлях також може бути вказаний як дескриптор відкритого файлу. Ця функція може не підтримуватися на вашій платформі; ви можете перевірити, чи він доступний, за допомогоюos.supports_fd
. Якщо він недоступний, його використання призведе до помилкиNotImplementedError
.Викликає подію аудиту
os.exec
з аргументамиpath
,args
,env
.Availability: Unix, Windows, not WASI, not Android, not iOS.
Berubah pada versi 3.3: Додано підтримку вказівки шляху як дескриптора відкритого файлу для
execve()
.Berubah pada versi 3.6: Menerima sebuah path-like object.
- os._exit(n)¶
Вийдіть із процесу зі статусом n, без виклику обробників очищення, очищення буферів stdio тощо.
Catatan
The standard way to exit is
sys.exit(n)
._exit()
should normally only be used in the child process after afork()
.
Наступні коди виходу визначені та можуть використовуватися з _exit()
, хоча вони не є обов’язковими. Зазвичай вони використовуються для системних програм, написаних мовою Python, таких як зовнішня програма доставки команд поштового сервера.
Catatan
Bazı değişkenlikler olduğundan, bunlardan bazıları tüm Unix platformlarında mevcut olmayabilir. Bu sabitler, temel alınan platform tarafından tanımlandıkları yerde tanımlanır.
- 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.Availability: Unix, Windows.
- os.EX_USAGE¶
Код виходу, який означає, що команда була використана неправильно, наприклад, коли вказано неправильну кількість аргументів.
Availability: Unix, not WASI.
- os.EX_DATAERR¶
Код виходу, який означає, що введені дані були неправильними.
Availability: Unix, not WASI.
- os.EX_NOINPUT¶
Код виходу, який означає, що вхідний файл не існував або не читався.
Availability: Unix, not WASI.
- os.EX_NOUSER¶
Код виходу, який означає, що вказаний користувач не існував.
Availability: Unix, not WASI.
- os.EX_NOHOST¶
Код виходу, який означає, що вказаний хост не існував.
Availability: Unix, not WASI.
- os.EX_UNAVAILABLE¶
Код виходу, який означає, що потрібна послуга недоступна.
Availability: Unix, not WASI.
- os.EX_SOFTWARE¶
Код виходу, який означає, що виявлено внутрішню помилку програмного забезпечення.
Availability: Unix, not WASI.
- os.EX_OSERR¶
Код виходу, який означає, що виявлено помилку операційної системи, наприклад неможливість розгалуження або створення каналу.
Availability: Unix, not WASI.
- os.EX_OSFILE¶
Код виходу, який означає, що якийсь системний файл не існував, його неможливо відкрити або якийсь інший тип помилки.
Availability: Unix, not WASI.
- os.EX_CANTCREAT¶
Код виходу означає, що вказаний користувачем вихідний файл неможливо створити.
Availability: Unix, not WASI.
- os.EX_IOERR¶
Код виходу, який означає, що сталася помилка під час виконання вводу-виводу для деякого файлу.
Availability: Unix, not WASI.
- os.EX_TEMPFAIL¶
Код виходу, який означає, що стався тимчасовий збій. Це вказує на те, що насправді не може бути помилкою, наприклад мережеве підключення, яке не вдалося встановити під час повторної операції.
Availability: Unix, not WASI.
- os.EX_PROTOCOL¶
Код виходу, який означає, що обмін протоколом був незаконним, недійсним або незрозумілим.
Availability: Unix, not WASI.
- os.EX_NOPERM¶
Код виходу, який означає, що було недостатньо дозволів для виконання операції (але не призначений для проблем файлової системи).
Availability: Unix, not WASI.
- os.EX_CONFIG¶
Код виходу, який означає, що сталася якась помилка конфігурації.
Availability: Unix, not WASI.
- os.EX_NOTFOUND¶
Код виходу, який означає щось на зразок "запис не знайдено".
Availability: Unix, not WASI.
- os.fork()¶
Розгалужуйте дочірній процес. Повертає
0
у дочірньому процесі та ідентифікатор дочірнього процесу в батьківському. У разі виникнення помилки виникаєOSError
.Зауважте, що деякі платформи, включаючи FreeBSD <= 6.3 і Cygwin, мають відомі проблеми під час використання
fork()
із потоку.Викликає подію аудиту
os.fork
без аргументів.Peringatan
If you use TLS sockets in an application calling
fork()
, see the warning in thessl
documentation.Peringatan
On macOS the use of this function is unsafe when mixed with using higher-level system APIs, and that includes using
urllib.request
.Berubah pada versi 3.8: Виклик
fork()
у підінтерпретаторі більше не підтримується (виникаєRuntimeError
).Berubah pada versi 3.12: If Python is able to detect that your process has multiple threads,
os.fork()
now raises aDeprecationWarning
.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 asmalloc
andfree
).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 WASI, not Android, not iOS.
- os.forkpty()¶
Розгалужуйте дочірній процес, використовуючи новий псевдотермінал як керуючий термінал дочірнього процесу. Повертає пару
(pid, fd)
, де pid є0
у дочірньому, ідентифікатор нового дочірнього процесу в батьківському, а fd є дескриптором файлу головного кінця псевдотермінал. Для більш портативного підходу використовуйте модульpty
. У разі виникнення помилки виникаєOSError
.Викликає подію аудиту
os.forkpty
без аргументів.Peringatan
On macOS the use of this function is unsafe when mixed with using higher-level system APIs, and that includes using
urllib.request
.Berubah pada versi 3.8: Виклик
forkpty()
у підінтерпретаторі більше не підтримується (виникаєRuntimeError
).Berubah pada versi 3.12: If Python is able to detect that your process has multiple threads, this now raises a
DeprecationWarning
. See the longer explanation onos.fork()
.Availability: Unix, not WASI, not Android, not iOS.
- os.kill(pid, sig, /)¶
Надішліть сигнал sig процесу pid. Константи для конкретних сигналів, доступних на хост-платформі, визначаються в модулі
signal
.Windows: The
signal.CTRL_C_EVENT
andsignal.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.Дивіться також
signal.pthread_kill()
.Викликає подію аудиту
os.kill
з аргументамиpid
,sig
.Availability: Unix, Windows, not WASI, not iOS.
Berubah pada versi 3.2: Dodano wsparcie dla WIndowsa.
- os.killpg(pgid, sig, /)¶
Надішліть сигнал sig до групи процесів pgid.
Викликає подію аудиту
os.killpg
з аргументамиpgid
,sig
.Availability: Unix, not WASI, not iOS.
- os.nice(increment, /)¶
Додайте приріст до "витонченості" процесу. Поверніть нову привабливість.
Availability: Unix, 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, Android >=
build-time
API level 31Added in version 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
Added in version 3.12.
- os.plock(op, /)¶
Блокування сегментів програми в пам'яті. Значення op (визначене в
<sys/lock.h>
) визначає, які сегменти заблоковано.Availability: Unix, not WASI, not iOS.
- 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-inopen()
function. The returned file object reads or writes text strings rather than bytes.Метод
close
повертаєNone
, якщо підпроцес завершився успішно, або код повернення підпроцесу, якщо сталася помилка. У системах POSIX, якщо код повернення позитивний, він представляє значення, що повертається процесом, зміщене вліво на один байт. Якщо код повернення від’ємний, це означає, що процес було припинено за допомогою сигналу, поданого зведеним значенням коду повернення. (Наприклад, значення, що повертається, може бути- signal.SIGKILL
, якщо підпроцес було закрито.) У системах Windows значення, що повертається, містить цілочисельний код повернення зі знаком від дочірнього процесу.В Unix
waitstatus_to_exitcode()
можна використовувати для перетворення результату методуclose
(статус виходу) у код виходу, якщо він неNone
. У Windows результатом методуclose
є безпосередньо код виходу (абоNone
).Це реалізовано за допомогою
subprocess.Popen
; перегляньте документацію цього класу, щоб дізнатися про більш потужні способи керування підпроцесами та спілкування з ними.Availability: not WASI, not Android, not iOS.
Catatan
The Python UTF-8 Mode affects encodings used for cmd and pipe contents.
popen()
is a simple wrapper aroundsubprocess.Popen
. Usesubprocess.Popen
orsubprocess.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.Більшість користувачів повинні використовувати
subprocess.run()
замістьposix_spawn()
.The positional-only arguments path, args, and env are similar to
execve()
. env is allowed to beNone
, in which case current process' environment is used.Параметр path — це шлях до виконуваного файлу. Шлях має містити каталог. Використовуйте
posix_spawnp()
, щоб передати виконуваний файл без каталогу.Аргумент file_actions може бути послідовністю кортежів, що описують дії, які потрібно виконати над певними дескрипторами файлів у дочірньому процесі між кроками
fork()
іexec()
реалізації бібліотеки C. Перший елемент у кожному кортежі має бути одним із трьох наведених нижче індикаторів типу, що описують інші елементи кортежу:- os.POSIX_SPAWN_OPEN¶
(
os.POSIX_SPAWN_OPEN
, fd, шлях, прапори, режим)Виконує
os.dup2(os.open(path, flags, mode), fd)
.
- os.POSIX_SPAWN_CLOSE¶
(
os.POSIX_SPAWN_CLOSE
, fd)Performs
os.close(fd)
.
- os.POSIX_SPAWN_DUP2¶
(
os.POSIX_SPAWN_DUP2
, fd, new_fd)Виконує
os.dup2(fd, new_fd)
.
- os.POSIX_SPAWN_CLOSEFROM¶
(
os.POSIX_SPAWN_CLOSEFROM
, fd)Performs
os.closerange(fd, INF)
.
These tuples correspond to the C library
posix_spawn_file_actions_addopen()
,posix_spawn_file_actions_addclose()
,posix_spawn_file_actions_adddup2()
, andposix_spawn_file_actions_addclosefrom_np()
API calls used to prepare for theposix_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 isFalse
, 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 libraryPOSIX_SPAWN_RESETIDS
flag.If the setsid argument is
True
, it will create a new session ID forposix_spawn
. setsid requiresPOSIX_SPAWN_SETSID
orPOSIX_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 ofNone
in the place of the scheduler policy indicates that is not being provided. This argument is a combination of the C libraryPOSIX_SPAWN_SETSCHEDPARAM
andPOSIX_SPAWN_SETSCHEDULER
flags.Викликає подію аудиту
os.posix_spawn
з аргументамиpath
,argv
,env
.Added in version 3.8.
Berubah pada versi 3.13: env parameter accepts
None
.os.POSIX_SPAWN_CLOSEFROM
is available on platforms whereposix_spawn_file_actions_addclosefrom_np()
exists.Availability: Unix, not WASI, not Android, not iOS.
- 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.Подібно до
posix_spawn()
, за винятком того, що система шукає виконуваний файл у списку каталогів, визначених змінною середовищаPATH
(так само, як і дляexecvp(3)
).Викликає подію аудиту
os.posix_spawn
з аргументамиpath
,argv
,env
.Added in version 3.8.
Availability: POSIX, not WASI, not Android, not iOS.
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 — це функція, яка викликається з дочірнього процесу.
Ці виклики здійснюються лише в тому випадку, якщо очікується, що контроль повернеться до інтерпретатора Python. Типовий запуск підпроцесу
subprocess
не запустить їх, оскільки дитина не збирається повторно входити в інтерпретатор.Функції, зареєстровані для виконання перед розгалуженням, викликаються у зворотному порядку реєстрації. Функції, зареєстровані для виконання після розгалуження (або в батьківському, або в дочірньому) викликаються в порядку реєстрації.
Зауважте, що виклики
fork()
, здійснені стороннім C-кодом, можуть не викликати ці функції, якщо тільки вони явно не викликаютьPyOS_BeforeFork()
,PyOS_AfterFork_Parent()
іPyOS_AfterFork_Child()
.Немає способу скасувати реєстрацію функції.
Availability: Unix, not WASI, not Android, not iOS.
Added in version 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)¶
Виконайте шлях програми в новому процесі.
(Зверніть увагу, що модуль
subprocess
надає потужніші можливості для створення нових процесів і отримання їх результатів; використання цього модуля є кращим, ніж використання цих функцій. Особливо перевірте розділ Replacing Older Functions with the subprocess Module.)Якщо mode
P_NOWAIT
, ця функція повертає ідентифікатор процесу нового процесу; якщо mode дорівнюєP_WAIT
, повертає код виходу процесу, якщо він завершується нормально, або-signal
, де signal є сигналом, який зупинив процес. У Windows ідентифікатор процесу фактично буде ідентифікатором процесу, тому його можна використовувати з функцієюwaitpid()
.Зверніть увагу на VxWorks, ця функція не повертає
-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 thespawnl*()
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
змінна середовища для пошуку файлу програми. Під час заміни середовища (з використанням одного з варіантів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)
Викликає подію аудиту
os.spawn
з аргументамиmode
,path
,args
,env
.Availability: Unix, Windows, not WASI, not Android, not iOS.
spawnlp()
,spawnlpe()
,spawnvp()
andspawnvpe()
are not available on Windows.spawnle()
andspawnve()
are not thread-safe on Windows; we advise you to use thesubprocess
module instead.Berubah pada versi 3.6: Menerima sebuah path-like object.
- 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, thespawn*
functions will return as soon as the new process has been created, with the process id as the return value.Availability: Unix, Windows.
- os.P_WAIT¶
Possible value for the mode parameter to the
spawn*
family of functions. If this is given as mode, thespawn*
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.Availability: Unix, Windows.
- os.P_DETACH¶
- os.P_OVERLAY¶
Можливі значення для параметра mode для сімейства функцій
spawn*
. Вони менш портативні, ніж перелічені вище.P_DETACH
подібний доP_NOWAIT
, але новий процес від’єднується від консолі процесу, що викликає. ЯкщоP_OVERLAY
використовується, поточний процес буде замінено; функціяspawn*
не повернеться.Availability: Windows.
- 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 ('/'
) Usepathlib
or theos.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.Викликає подію аудиту
os.startfile
з аргументамиpath
,operation
.Raises an auditing event
os.startfile/2
with argumentspath
,operation
,arguments
,cwd
,show_cmd
.Availability: Windows.
Berubah pada versi 3.10: Added the arguments, cwd and show_cmd arguments, and the
os.startfile/2
audit event.
- os.system(command)¶
Виконайте команду (рядок) у підоболонці. Це реалізується шляхом виклику стандартної функції C
system()
і має ті самі обмеження. Зміни вsys.stdin
тощо не відображаються в середовищі виконуваної команди. Якщо команда генерує будь-який вихід, він буде надісланий до стандартного потоку виводу інтерпретатора. Стандарт C не визначає значення значення, що повертається функцією C, тому значення, що повертається функцією Python, залежить від системи.В Unix значення, що повертається, є статусом завершення процесу, закодованим у форматі, указаному для
wait()
.У Windows повертається значення, яке повертає системна оболонка після виконання команди. Оболонка визначається змінною середовища Windows
COMSPEC
: зазвичай це cmd.exe, яка повертає статус завершення виконання команди; у системах, які використовують нерідну оболонку, зверніться до документації вашої оболонки.The
subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in thesubprocess
documentation for some helpful recipes.В Unix
waitstatus_to_exitcode()
можна використовувати для перетворення результату (статус виходу) у код виходу. У Windows результатом є безпосередньо код виходу.Викликає подію аудиту
os.system
з аргументомcommand
.Availability: Unix, Windows, not WASI, not Android, not iOS.
- os.times()¶
Повертає поточний глобальний час процесу. Повернене значення є об’єктом із п’ятьма атрибутами:
user
- час користувачаsystem
- системний часchildren_user
- час користувача всіх дочірніх процесівchildren_system
- системний час усіх дочірніх процесівelapsed
- реальний час, що минув від фіксованої точки в минулому
Для зворотної сумісності цей об’єкт також поводиться як п’ять кортежів, що містять
user
,system
,children_user
,children_system
іминало
в такому порядку.See the Unix manual page times(2) and times(3) manual page on Unix or the GetProcessTimes MSDN on Windows. On Windows, only
user
andsystem
are known; the other attributes are zero.Availability: Unix, Windows.
Berubah pada versi 3.3: Return type changed from a tuple to a tuple-like object with named attributes.
- os.wait()¶
Зачекайте на завершення дочірнього процесу та поверніть кортеж, що містить його pid та індикацію статусу виходу: 16-розрядне число, чий молодший байт є номером сигналу, що вбив процес, а старший байт є статусом виходу (якщо сигнал число дорівнює нулю); старший біт молодшого байта встановлюється, якщо було створено основний файл.
If there are no children that could be waited for,
ChildProcessError
is raised.waitstatus_to_exitcode()
можна використовувати для перетворення статусу виходу в код виходу.Availability: Unix, not WASI, not Android, not iOS.
Lihat juga
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
orWCONTINUED
is required;WNOHANG
andWNOWAIT
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
(alwaysSIGCHLD
)si_status
(the exit status or signal number, depending onsi_code
)si_code
(seeCLD_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 WASI, not Android, not iOS.
Added in version 3.3.
Berubah pada versi 3.13: This function is now available on macOS as well.
- os.waitpid(pid, options, /)¶
Bu işlevin ayrıntıları Unix ve Windows'ta farklılık gösterir.
В Unix: зачекайте на завершення дочірнього процесу, заданого ідентифікатором процесу pid, і поверніть кортеж, що містить ідентифікатор його процесу та вказівку статусу виходу (закодовано як для
wait()
). На семантику виклику впливає значення цілого числа options, яке має бути0
для нормальної роботи.Якщо pid більший за
0
,waitpid()
запитує інформацію про статус для цього конкретного процесу. Якщо pid дорівнює0
, запит стосується статусу будь-якого дочірнього елемента в групі поточного процесу. Якщо 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 areWUNTRACED
andWCONTINUED
.У Windows: дочекайтеся завершення процесу, заданого дескриптором процесу pid, і поверніть кортеж, що містить pid, а його статус виходу зміщений вліво на 8 біт (зміщення полегшує використання функції на різних платформах). pid менше або дорівнює
0
не має особливого значення в Windows і викликає виключення. Значення цілого параметра не впливає. pid може посилатися на будь-який процес, ідентифікатор якого відомий, не обов’язково дочірній процес. Функціїspawn*
, викликані за допомогоюP_NOWAIT
, повертають відповідні дескриптори процесу.waitstatus_to_exitcode()
можна використовувати для перетворення статусу виходу в код виходу.Availability: Unix, Windows, not WASI, not Android, not iOS.
Berubah pada versi 3.5: Jika panggilan sistem terganggu dan penangan sinyal tidak menimbulkan pengecualian, fungsi sekarang mencoba ulang panggilan sistem alih-alih menimbulkan pengecualian
InterruptedError
(lihat PEP 475 untuk penjelasannya).
- 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 toresource.getrusage()
for details on resource usage information. The options argument is the same as that provided towaitpid()
andwait4()
.waitstatus_to_exitcode()
можна використовувати для перетворення статусу виходу в код виходу.Availability: Unix, not WASI, not Android, not iOS.
- 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 toresource.getrusage()
for details on resource usage information. The arguments towait4()
are the same as those provided towaitpid()
.waitstatus_to_exitcode()
можна використовувати для перетворення статусу виходу в код виходу.Availability: Unix, not WASI, not Android, not iOS.
- 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 withpidfd_open()
).
Availability: Unix, not WASI, not Android, not iOS.
Catatan
P_PIDFD
is only available on Linux >= 5.4.Added in version 3.3.
Added in version 3.9: The
P_PIDFD
constant.
- os.WCONTINUED¶
This options flag for
waitpid()
,wait3()
,wait4()
, andwaitid()
causes child processes to be reported if they have been continued from a job control stop since they were last reported.Availability: Unix, not WASI, not Android, not iOS.
- 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 WASI, not Android, not iOS.
Added in version 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 WASI, not Android, not iOS.
Added in version 3.3.
- os.WUNTRACED¶
This options flag for
waitpid()
,wait3()
, andwait4()
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 WASI, not Android, not iOS.
- os.WNOHANG¶
This options flag causes
waitpid()
,wait3()
,wait4()
, andwaitid()
to return right away if no child process status is available immediately.Availability: Unix, not WASI, not Android, not iOS.
- os.WNOWAIT¶
This options flag causes
waitid()
to leave the child in a waitable state, so that a laterwait*()
call can be used to retrieve the child status information again.This option is not available for the other
wait*
functions.Availability: Unix, not WASI, not Android, not iOS.
- 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 bywaitid()
.Availability: Unix, not WASI, not Android, not iOS.
Added in version 3.3.
Berubah pada versi 3.9: Додано значення
CLD_KILLED
іCLD_STOPPED
.
- os.waitstatus_to_exitcode(status)¶
Перетворення статусу очікування на код виходу.
Unix'te:
Якщо процес закінчився нормально (якщо
WIFEXITED(статус)
має значення true), повертає статус виходу процесу (повертаєWEXITSTATUS(статус)
): результат більше або дорівнює 0.Якщо процес було припинено через сигнал (якщо
WIFSIGNALED(status)
має значення true), повертає-signum
, де signum — це номер сигналу, який спричинив завершення процесу (повертає- WTERMSIG(статус)
): результат менше 0.Інакше викличте
ValueError
.
У Windows повертає статус, зміщений праворуч на 8 біт.
В Unix, якщо процес відстежується або якщо
waitpid()
було викликано з опцієюWUNTRACED
, абонент повинен спочатку перевірити, чиWIFSTOPPED(status)
є істинним. Цю функцію не можна викликати, якщоWIFSTOPPED(статус)
має значення true.Lihat juga
Функції
WIFEXITED()
,WEXITSTATUS()
,WIFSIGNALED()
,WTERMSIG()
,WIFSTOPPED()
,WSTOPSIG()
.Availability: Unix, Windows, not WASI, not Android, not iOS.
Added in version 3.9.
Наступні функції приймають код стану процесу, який повертає system()
, wait()
або waitpid()
як параметр. Вони можуть бути використані для визначення розташування процесу.
- os.WCOREDUMP(status, /)¶
Повертає
True
, якщо для процесу було створено дамп ядра, інакше повертаєFalse
.Цю функцію слід використовувати, лише якщо
WIFSIGNALED()
має значення true.Availability: Unix, not WASI, not Android, not iOS.
- os.WIFCONTINUED(status)¶
Return
True
if a stopped child has been resumed by delivery ofSIGCONT
(if the process has been continued from a job control stop), otherwise returnFalse
.Перегляньте параметр
WCONTINUED
.Availability: Unix, not WASI, not Android, not iOS.
- os.WIFSTOPPED(status)¶
Повертає
True
, якщо процес було зупинено доставкою сигналу, інакше повертаєFalse
.WIFSTOPPED()
повертаєTrue
, лише якщо викликwaitpid()
було виконано за допомогою параметраWUNTRACED
або коли процес відстежується (див. ptrace(2) ).Availability: Unix, not WASI, not Android, not iOS.
- os.WIFSIGNALED(status)¶
Повертає
True
, якщо процес було припинено сигналом, інакше повертаєFalse
.Availability: Unix, not WASI, not Android, not iOS.
- os.WIFEXITED(status)¶
Повертає
True
, якщо процес завершився нормально, тобто викликомexit()
чи_exit()
, або шляхом повернення зmain()
; інакше повертаєFalse
.Availability: Unix, not WASI, not Android, not iOS.
- os.WEXITSTATUS(status)¶
Повернути статус виходу процесу.
Цю функцію слід використовувати, лише якщо
WIFEXITED()
має значення true.Availability: Unix, not WASI, not Android, not iOS.
- os.WSTOPSIG(status)¶
Повернути сигнал, який спричинив зупинку процесу.
Цю функцію слід використовувати, лише якщо
WIFSTOPPED()
має значення true.Availability: Unix, not WASI, not Android, not iOS.
- os.WTERMSIG(status)¶
Повертає номер сигналу, який викликав завершення процесу.
Цю функцію слід використовувати, лише якщо
WIFSIGNALED()
має значення true.Availability: Unix, not WASI, not Android, not iOS.
Інтерфейс до планувальника¶
Bu işlevler, işletim sistemi tarafından bir işlemeye CPU zamanının nasıl tahsis edildiğini kontrol eder. Yalnızca bazı Unix platformlarında mevcutturlar. Daha ayrıntılı bilgi için Unix kılavuz sayfalarınıza bakın.
Added in version 3.3.
Наведені нижче політики планування доступні, якщо вони підтримуються операційною системою.
- os.SCHED_OTHER¶
Політика планування за умовчанням.
- os.SCHED_BATCH¶
Політика планування процесів із інтенсивним використанням ЦП, яка намагається зберегти інтерактивність решти комп’ютера.
- os.SCHED_IDLE¶
Політика планування для фонових завдань із надзвичайно низьким пріоритетом.
- os.SCHED_SPORADIC¶
Політика планування для спорадичних серверних програм.
- os.SCHED_FIFO¶
Політика планування за принципом "перший прийшов - перший вийшов".
- os.SCHED_RR¶
Політика циклічного планування.
- os.SCHED_RESET_ON_FORK¶
Цей прапорець можна об’єднати з будь-якою іншою політикою планування. Коли процес із цим прапорцем розгалужується, його політика планування та пріоритет скидаються до стандартних.
- class os.sched_param(sched_priority)¶
Цей клас представляє настроювані параметри планування, які використовуються в
sched_setparam()
,sched_setscheduler()
іsched_getparam()
. Це незмінно.На даний момент можливий лише один параметр:
- sched_priority¶
Пріоритет планування для політики планування.
- os.sched_get_priority_min(policy)¶
Отримайте мінімальне значення пріоритету для політики. policy є однією з наведених вище констант політики планування.
- os.sched_get_priority_max(policy)¶
Отримайте максимальне значення пріоритету для політики. policy є однією з наведених вище констант політики планування.
- os.sched_setscheduler(pid, policy, param, /)¶
Встановіть політику планування для процесу за допомогою PID pid. pid, рівний 0, означає процес виклику. policy — це одна з наведених вище констант політики планування. param є екземпляром
sched_param
.
- os.sched_getscheduler(pid, /)¶
Повернути політику планування для процесу з PID pid. pid, рівний 0, означає процес виклику. Результатом є одна з наведених вище констант політики планування.
- os.sched_setparam(pid, param, /)¶
Встановіть параметри планування для процесу за допомогою PID pid. pid, рівний 0, означає процес виклику. param є екземпляром
sched_param
.
- os.sched_getparam(pid, /)¶
Поверніть параметри планування як екземпляр
sched_param
для процесу з PID pid. pid, рівний 0, означає процес виклику.
- os.sched_rr_get_interval(pid, /)¶
Повертайте циклічний квант за секунди для процесу з PID pid. pid, рівний 0, означає процес виклику.
- os.sched_yield()¶
Voluntarily relinquish the CPU. See sched_yield(2) for details.
- os.sched_setaffinity(pid, mask, /)¶
Обмежте процес за допомогою PID pid (або поточного процесу, якщо дорівнює нулю) набору ЦП. mask — це ітерація цілих чисел, що представляють набір процесорів, якими має бути обмежений процес.
- 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.
See also the
process_cpu_count()
function.
Різна системна інформація¶
- os.confstr(name, /)¶
Повертає рядкові значення конфігурації системи. name вказує значення конфігурації для отримання; це може бути рядок, який є назвою визначеного системного значення; ці імена вказані в ряді стандартів (POSIX, Unix 95, Unix 98 та ін.). Деякі платформи також визначають додаткові імена. Імена, відомі головній операційній системі, надаються як ключі словника
confstr_names
. Для змінних конфігурації, не включених до цього відображення, також допускається передача цілого числа для name.Якщо значення конфігурації, указане name, не визначено, повертається
None
.Якщо name є рядком і невідоме, виникає
ValueError
. Якщо певне значення для name не підтримується хост-системою, навіть якщо воно включене вconfstr_names
, виникаєOSError
зerrno.EINVAL
для номера помилки .Availability: Unix.
- os.confstr_names¶
Словник зіставляє імена, прийняті
confstr()
, до цілих значень, визначених для цих імен головною операційною системою. Це можна використовувати для визначення набору імен, відомих системі.Availability: Unix.
- os.cpu_count()¶
Return the number of logical CPUs in the system. Returns
None
if undetermined.The
process_cpu_count()
function can be used to get the number of logical CPUs usable by the calling thread of the current process.Added in version 3.4.
Berubah pada versi 3.13: If
-X cpu_count
is given orPYTHON_CPU_COUNT
is set,cpu_count()
returns the overridden value n.
- os.getloadavg()¶
Повертає середню кількість процесів у черзі виконання системи за останні 1, 5 і 15 хвилин або викликає
OSError
, якщо середнє значення завантаження неможливо отримати.Availability: Unix.
- os.process_cpu_count()¶
Get the number of logical CPUs usable by the calling thread of the current process. Returns
None
if undetermined. It can be less thancpu_count()
depending on the CPU affinity.The
cpu_count()
function can be used to get the number of logical CPUs in the system.If
-X cpu_count
is given orPYTHON_CPU_COUNT
is set,process_cpu_count()
returns the overridden value n.See also the
sched_getaffinity()
function.Added in version 3.13.
- os.sysconf(name, /)¶
Повертає цілочисельні значення конфігурації системи. Якщо значення конфігурації, указане name, не визначено, повертається
-1
. Коментарі щодо параметра name дляconfstr()
також застосовуються тут; словник, який надає інформацію про відомі імена, надаєтьсяsysconf_names
.Availability: Unix.
- os.sysconf_names¶
Словник зіставляє імена, прийняті
sysconf()
, до цілих значень, визначених для цих імен головною операційною системою. Це можна використовувати для визначення набору імен, відомих системі.Availability: Unix.
Berubah pada versi 3.11: Add
'SC_MINSIGSTKSZ'
name.
Наступні значення даних використовуються для підтримки операцій маніпулювання шляхом. Вони визначені для всіх платформ.
Операції вищого рівня над іменами шляхів визначені в модулі os.path
.
- os.curdir¶
Постійний рядок, який використовується операційною системою для посилання на поточний каталог. Це
'.'
для Windows і POSIX. Також доступний черезos.path
.
- os.pardir¶
Постійний рядок, який використовується операційною системою для посилання на батьківський каталог. Це ".." для Windows і POSIX. Також доступний через
os.path
.
- os.sep¶
Символ, який використовується операційною системою для розділення компонентів шляху. Це
'/'
для POSIX і'\\'
для Windows. Зауважте, що знати це недостатньо, щоб мати змогу розбирати або об’єднувати шляхи --- використовуйтеos.path.split()
іos.path.join()
--- але іноді це корисно. Також доступний черезos.path
.
- os.altsep¶
Альтернативний символ, який використовується операційною системою для розділення компонентів шляху, або "Немає", якщо існує лише один роздільний символ. У системах Windows встановлено значення
'/''
, деsep
є зворотною косою рискою. Також доступний черезos.path
.
- os.extsep¶
Символ, який відокремлює базову назву файлу від розширення; наприклад,
'.'
уos.py
. Також доступний черезos.path
.
- os.pathsep¶
Символ, який зазвичай використовується операційною системою для розділення компонентів шляху пошуку (як у
PATH
), наприклад':''
для POSIX або';''
для Windows. Також доступний черезos.path
.
- os.defpath¶
Шлях пошуку за умовчанням, який використовується
exec*p*
іspawn*p*
, якщо середовище не має ключа'PATH'
. Також доступний черезos.path
.
- os.linesep¶
Рядок, який використовується для розділення (точніше, завершення) рядків на поточній платформі. Це може бути один символ, наприклад
'\n'
для POSIX, або кілька символів, наприклад'\r\n'
для Windows. Не використовуйте os.linesep як символ закінчення рядка під час запису файлів, відкритих у текстовому режимі (за замовчуванням); замість цього використовуйте єдиний'\n'
на всіх платформах.
- os.devnull¶
Шлях до файлу нульового пристрою. Наприклад:
'/dev/null
для POSIX,'nul'
для Windows. Також доступний через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()
. Що означають різні прапорці, див. сторінку посібника Unix dlopen(3).Added in version 3.3.
Rastgele sayılar¶
- 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
andGRND_NONBLOCK
.See also the Linux getrandom() manual page.
Availability: Linux >= 3.17.
Added in version 3.6.
- os.urandom(size, /)¶
Повертає байтовий рядок розміру випадкових байтів, придатних для криптографічного використання.
Ця функція повертає випадкові байти зі специфічного для ОС джерела випадковості. Повернуті дані мають бути досить непередбачуваними для криптографічних програм, хоча їх точна якість залежить від реалізації ОС.
У Linux, якщо доступний системний виклик
getrandom()
, він використовується в режимі блокування: блокуйте, доки системний пул випадкової ентропії не буде ініціалізовано (128 біт ентропії збирає ядро). Перегляньте PEP 524 для обґрунтування. У Linux функціяgetrandom()
може бути використана для отримання випадкових байтів у неблокуючому режимі (використовуючи прапорGRND_NONBLOCK
) або для опитування, доки системний пул випадкової ентропії не буде ініціалізовано.У Unix-подібній системі випадкові байти зчитуються з пристрою
/dev/urandom
. Якщо пристрій/dev/urandom
недоступний або не читається, виникає винятокNotImplementedError
.On Windows, it will use
BCryptGenRandom()
.Lihat juga
Модуль
secrets
забезпечує функції вищого рівня. Про простий у використанні інтерфейс генератора випадкових чисел, наданий вашою платформою, див.random.SystemRandom
.Berubah pada versi 3.5: У Linux 3.17 і новіших версіях системний виклик
getrandom()
тепер використовується, якщо він доступний. У OpenBSD 5.6 і новіших версіях тепер використовується функція Cgetentropy()
. Ці функції уникають використання внутрішнього файлового дескриптора.Berubah pada versi 3.5.2: У Linux, якщо системний виклик
getrandom()
блокує (пул ентропії urandom ще не ініціалізовано), поверніться до читання/dev/urandom
.Berubah pada versi 3.6: У Linux
getrandom()
тепер використовується в режимі блокування для підвищення безпеки.Berubah pada versi 3.11: On Windows,
BCryptGenRandom()
is used instead ofCryptGenRandom()
which is deprecated.
- os.GRND_NONBLOCK¶
За замовчуванням під час читання з
/dev/random
getrandom()
блокує, якщо випадкові байти недоступні, а під час читання з/dev/urandom
блокує, якщо пул ентропії не має ще не ініціалізовано.Якщо встановлено прапорець
GRND_NONBLOCK
, тоgetrandom()
не блокує в цих випадках, а замість цього негайно викликаєBlockingIOError
.Added in version 3.6.
- os.GRND_RANDOM¶
Якщо цей біт установлено, випадкові байти витягуються з пулу
/dev/random
замість пулу/dev/urandom
.Added in version 3.6.