Debian Codegraph @

Doc/library/os.rst

raw
1 :mod:`!os` --- Miscellaneous operating system interfaces
2 ========================================================
3
4 .. module:: os
5 :synopsis: Miscellaneous operating system interfaces.
6
7 **Source code:** :source:`Lib/os.py`
8
9 --------------
10
11 This module provides a portable way of using operating system dependent
12 functionality. If you just want to read or write a file see :func:`open`, if
13 you want to manipulate paths, see the :mod:`os.path` module, and if you want to
14 read all the lines in all the files on the command line see the :mod:`fileinput`
15 module. For creating temporary files and directories see the :mod:`tempfile`
16 module, and for high-level file and directory handling see the :mod:`shutil`
17 module.
18
19 Notes on the availability of these functions:
20
21 * The design of all built-in operating system dependent modules of Python is
22 such that as long as the same functionality is available, it uses the same
23 interface; for example, the function ``os.stat(path)`` returns stat
24 information about *path* in the same format (which happens to have originated
25 with the POSIX interface).
26
27 * Extensions peculiar to a particular operating system are also available
28 through the :mod:`os` module, but using them is of course a threat to
29 portability.
30
31 * All functions accepting path or file names accept both bytes and string
32 objects, and result in an object of the same type, if a path or file name is
33 returned.
34
35 * On VxWorks, os.popen, os.fork, os.execv and os.spawn*p* are not supported.
36
37 * On WebAssembly platforms, Android and iOS, large parts of the :mod:`os` module are
38 not available or behave differently. APIs related to processes (e.g.
39 :func:`~os.fork`, :func:`~os.execve`) and resources (e.g. :func:`~os.nice`)
40 are not available. Others like :func:`~os.getuid` and :func:`~os.getpid` are
41 emulated or stubs. WebAssembly platforms also lack support for signals (e.g.
42 :func:`~os.kill`, :func:`~os.wait`).
43
44
45 .. note::
46
47 All functions in this module raise :exc:`OSError` (or subclasses thereof) in
48 the case of invalid or inaccessible file names and paths, or other arguments
49 that have the correct type, but are not accepted by the operating system.
50
51 .. exception:: error
52
53 An alias for the built-in :exc:`OSError` exception.
54
55
56 .. data:: name
57
58 The name of the operating system dependent module imported. The following
59 names have currently been registered: ``'posix'``, ``'nt'``,
60 ``'java'``.
61
62 .. seealso::
63 :data:`sys.platform` has a finer granularity. :func:`os.uname` gives
64 system-dependent version information.
65
66 The :mod:`platform` module provides detailed checks for the
67 system's identity.
68
69
70 .. _os-filenames:
71 .. _filesystem-encoding:
72
73 File Names, Command Line Arguments, and Environment Variables
74 -------------------------------------------------------------
75
76 In Python, file names, command line arguments, and environment variables are
77 represented using the string type. On some systems, decoding these strings to
78 and from bytes is necessary before passing them to the operating system. Python
79 uses the :term:`filesystem encoding and error handler` to perform this
80 conversion (see :func:`sys.getfilesystemencoding`).
81
82 The :term:`filesystem encoding and error handler` are configured at Python
83 startup by the :c:func:`PyConfig_Read` function: see
84 :c:member:`~PyConfig.filesystem_encoding` and
85 :c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`.
86
87 .. versionchanged:: 3.1
88 On some systems, conversion using the file system encoding may fail. In this
89 case, Python uses the :ref:`surrogateescape encoding error handler
90 <surrogateescape>`, which means that undecodable bytes are replaced by a
91 Unicode character U+DC\ *xx* on decoding, and these are again
92 translated to the original byte on encoding.
93
94
95 The :term:`file system encoding <filesystem encoding and error handler>` must
96 guarantee to successfully decode all bytes below 128. If the file system
97 encoding fails to provide this guarantee, API functions can raise
98 :exc:`UnicodeError`.
99
100 See also the :term:`locale encoding`.
101
102
103 .. _utf8-mode:
104
105 Python UTF-8 Mode
106 -----------------
107
108 .. versionadded:: 3.7
109 See :pep:`540` for more details.
110
111 The Python UTF-8 Mode ignores the :term:`locale encoding` and forces the usage
112 of the UTF-8 encoding:
113
114 * Use UTF-8 as the :term:`filesystem encoding <filesystem encoding and error
115 handler>`.
116 * :func:`sys.getfilesystemencoding` returns ``'utf-8'``.
117 * :func:`locale.getpreferredencoding` returns ``'utf-8'`` (the *do_setlocale*
118 argument has no effect).
119 * :data:`sys.stdin`, :data:`sys.stdout`, and :data:`sys.stderr` all use
120 UTF-8 as their text encoding, with the ``surrogateescape``
121 :ref:`error handler <error-handlers>` being enabled for :data:`sys.stdin`
122 and :data:`sys.stdout` (:data:`sys.stderr` continues to use
123 ``backslashreplace`` as it does in the default locale-aware mode)
124 * On Unix, :func:`os.device_encoding` returns ``'utf-8'`` rather than the
125 device encoding.
126
127 Note that the standard stream settings in UTF-8 mode can be overridden by
128 :envvar:`PYTHONIOENCODING` (just as they can be in the default locale-aware
129 mode).
130
131 As a consequence of the changes in those lower level APIs, other higher
132 level APIs also exhibit different default behaviours:
133
134 * Command line arguments, environment variables and filenames are decoded
135 to text using the UTF-8 encoding.
136 * :func:`os.fsdecode` and :func:`os.fsencode` use the UTF-8 encoding.
137 * :func:`open`, :func:`io.open`, and :func:`codecs.open` use the UTF-8
138 encoding by default. However, they still use the strict error handler by
139 default so that attempting to open a binary file in text mode is likely
140 to raise an exception rather than producing nonsense data.
141
142 The :ref:`Python UTF-8 Mode <utf8-mode>` is enabled if the LC_CTYPE locale is
143 ``C`` or ``POSIX`` at Python startup (see the :c:func:`PyConfig_Read`
144 function).
145
146 It can be enabled or disabled using the :option:`-X utf8 <-X>` command line
147 option and the :envvar:`PYTHONUTF8` environment variable.
148
149 If the :envvar:`PYTHONUTF8` environment variable is not set at all, then the
150 interpreter defaults to using the current locale settings, *unless* the current
151 locale is identified as a legacy ASCII-based locale (as described for
152 :envvar:`PYTHONCOERCECLOCALE`), and locale coercion is either disabled or
153 fails. In such legacy locales, the interpreter will default to enabling UTF-8
154 mode unless explicitly instructed not to do so.
155
156 The Python UTF-8 Mode can only be enabled at the Python startup. Its value
157 can be read from :data:`sys.flags.utf8_mode <sys.flags>`.
158
159 See also the :ref:`UTF-8 mode on Windows <win-utf8-mode>`
160 and the :term:`filesystem encoding and error handler`.
161
162 .. seealso::
163
164 :pep:`686`
165 Python 3.15 will make :ref:`utf8-mode` default.
166
167
168 .. _os-procinfo:
169
170 Process Parameters
171 ------------------
172
173 These functions and data items provide information and operate on the current
174 process and user.
175
176
177 .. function:: ctermid()
178
179 Return the filename corresponding to the controlling terminal of the process.
180
181 .. availability:: Unix, not WASI.
182
183
184 .. data:: environ
185
186 A :term:`mapping` object where keys and values are strings that represent
187 the process environment. For example, ``environ['HOME']`` is the pathname
188 of your home directory (on some platforms), and is equivalent to
189 ``getenv("HOME")`` in C.
190
191 This mapping is captured the first time the :mod:`os` module is imported,
192 typically during Python startup as part of processing :file:`site.py`. Changes
193 to the environment made after this time are not reflected in :data:`os.environ`,
194 except for changes made by modifying :data:`os.environ` directly.
195
196 This mapping may be used to modify the environment as well as query the
197 environment. :func:`putenv` will be called automatically when the mapping
198 is modified.
199
200 On Unix, keys and values use :func:`sys.getfilesystemencoding` and
201 ``'surrogateescape'`` error handler. Use :data:`environb` if you would like
202 to use a different encoding.
203
204 On Windows, the keys are converted to uppercase. This also applies when
205 getting, setting, or deleting an item. For example,
206 ``environ['monty'] = 'python'`` maps the key ``'MONTY'`` to the value
207 ``'python'``.
208
209 .. note::
210
211 Calling :func:`putenv` directly does not change :data:`os.environ`, so it's better
212 to modify :data:`os.environ`.
213
214 .. note::
215
216 On some platforms, including FreeBSD and macOS, setting ``environ`` may
217 cause memory leaks. Refer to the system documentation for
218 :c:func:`!putenv`.
219
220 You can delete items in this mapping to unset environment variables.
221 :func:`unsetenv` will be called automatically when an item is deleted from
222 :data:`os.environ`, and when one of the :meth:`pop` or :meth:`clear` methods is
223 called.
224
225 .. versionchanged:: 3.9
226 Updated to support :pep:`584`'s merge (``|``) and update (``|=``) operators.
227
228
229 .. data:: environb
230
231 Bytes version of :data:`environ`: a :term:`mapping` object where both keys
232 and values are :class:`bytes` objects representing the process environment.
233 :data:`environ` and :data:`environb` are synchronized (modifying
234 :data:`environb` updates :data:`environ`, and vice versa).
235
236 :data:`environb` is only available if :const:`supports_bytes_environ` is
237 ``True``.
238
239 .. versionadded:: 3.2
240
241 .. versionchanged:: 3.9
242 Updated to support :pep:`584`'s merge (``|``) and update (``|=``) operators.
243
244
245 .. function:: chdir(path)
246 fchdir(fd)
247 getcwd()
248 :noindex:
249
250 These functions are described in :ref:`os-file-dir`.
251
252
253 .. function:: fsencode(filename)
254
255 Encode :term:`path-like <path-like object>` *filename* to the
256 :term:`filesystem encoding and error handler`; return :class:`bytes`
257 unchanged.
258
259 :func:`fsdecode` is the reverse function.
260
261 .. versionadded:: 3.2
262
263 .. versionchanged:: 3.6
264 Support added to accept objects implementing the :class:`os.PathLike`
265 interface.
266
267
268 .. function:: fsdecode(filename)
269
270 Decode the :term:`path-like <path-like object>` *filename* from the
271 :term:`filesystem encoding and error handler`; return :class:`str`
272 unchanged.
273
274 :func:`fsencode` is the reverse function.
275
276 .. versionadded:: 3.2
277
278 .. versionchanged:: 3.6
279 Support added to accept objects implementing the :class:`os.PathLike`
280 interface.
281
282
283 .. function:: fspath(path)
284
285 Return the file system representation of the path.
286
287 If :class:`str` or :class:`bytes` is passed in, it is returned unchanged.
288 Otherwise :meth:`~os.PathLike.__fspath__` is called and its value is
289 returned as long as it is a :class:`str` or :class:`bytes` object.
290 In all other cases, :exc:`TypeError` is raised.
291
292 .. versionadded:: 3.6
293
294
295 .. class:: PathLike
296
297 An :term:`abstract base class` for objects representing a file system path,
298 e.g. :class:`pathlib.PurePath`.
299
300 .. versionadded:: 3.6
301
302 .. method:: __fspath__()
303 :abstractmethod:
304
305 Return the file system path representation of the object.
306
307 The method should only return a :class:`str` or :class:`bytes` object,
308 with the preference being for :class:`str`.
309
310
311 .. function:: getenv(key, default=None)
312
313 Return the value of the environment variable *key* as a string if it exists, or
314 *default* if it doesn't. *key* is a string. Note that
315 since :func:`getenv` uses :data:`os.environ`, the mapping of :func:`getenv` is
316 similarly also captured on import, and the function may not reflect
317 future environment changes.
318
319 On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding`
320 and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you
321 would like to use a different encoding.
322
323 .. availability:: Unix, Windows.
324
325
326 .. function:: getenvb(key, default=None)
327
328 Return the value of the environment variable *key* as bytes if it exists, or
329 *default* if it doesn't. *key* must be bytes. Note that
330 since :func:`getenvb` uses :data:`os.environb`, the mapping of :func:`getenvb` is
331 similarly also captured on import, and the function may not reflect
332 future environment changes.
333
334
335 :func:`getenvb` is only available if :const:`supports_bytes_environ`
336 is ``True``.
337
338 .. availability:: Unix.
339
340 .. versionadded:: 3.2
341
342
343 .. function:: get_exec_path(env=None)
344
345 Returns the list of directories that will be searched for a named
346 executable, similar to a shell, when launching a process.
347 *env*, when specified, should be an environment variable dictionary
348 to lookup the PATH in.
349 By default, when *env* is ``None``, :data:`environ` is used.
350
351 .. versionadded:: 3.2
352
353
354 .. function:: getegid()
355
356 Return the effective group id of the current process. This corresponds to the
357 "set id" bit on the file being executed in the current process.
358
359 .. availability:: Unix, not WASI.
360
361
362 .. function:: geteuid()
363
364 .. index:: single: user; effective id
365
366 Return the current process's effective user id.
367
368 .. availability:: Unix, not WASI.
369
370
371 .. function:: getgid()
372
373 .. index:: single: process; group
374
375 Return the real group id of the current process.
376
377 .. availability:: Unix.
378
379 The function is a stub on WASI, see :ref:`wasm-availability` for more
380 information.
381
382
383 .. function:: getgrouplist(user, group, /)
384
385 Return list of group ids that *user* belongs to. If *group* is not in the
386 list, it is included; typically, *group* is specified as the group ID
387 field from the password record for *user*, because that group ID will
388 otherwise be potentially omitted.
389
390 .. availability:: Unix, not WASI.
391
392 .. versionadded:: 3.3
393
394
395 .. function:: getgroups()
396
397 Return list of supplemental group ids associated with the current process.
398
399 .. availability:: Unix, not WASI.
400
401 .. note::
402
403 On macOS, :func:`getgroups` behavior differs somewhat from
404 other Unix platforms. If the Python interpreter was built with a
405 deployment target of ``10.5`` or earlier, :func:`getgroups` returns
406 the list of effective group ids associated with the current user process;
407 this list is limited to a system-defined number of entries, typically 16,
408 and may be modified by calls to :func:`setgroups` if suitably privileged.
409 If built with a deployment target greater than ``10.5``,
410 :func:`getgroups` returns the current group access list for the user
411 associated with the effective user id of the process; the group access
412 list may change over the lifetime of the process, it is not affected by
413 calls to :func:`setgroups`, and its length is not limited to 16. The
414 deployment target value, :const:`MACOSX_DEPLOYMENT_TARGET`, can be
415 obtained with :func:`sysconfig.get_config_var`.
416
417
418 .. function:: getlogin()
419
420 Return the name of the user logged in on the controlling terminal of the
421 process. For most purposes, it is more useful to use
422 :func:`getpass.getuser` since the latter checks the environment variables
423 :envvar:`LOGNAME` or :envvar:`USERNAME` to find out who the user is, and
424 falls back to ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the
425 current real user id.
426
427 .. availability:: Unix, Windows, not WASI.
428
429
430 .. function:: getpgid(pid)
431
432 Return the process group id of the process with process id *pid*. If *pid* is 0,
433 the process group id of the current process is returned.
434
435 .. availability:: Unix, not WASI.
436
437 .. function:: getpgrp()
438
439 .. index:: single: process; group
440
441 Return the id of the current process group.
442
443 .. availability:: Unix, not WASI.
444
445
446 .. function:: getpid()
447
448 .. index:: single: process; id
449
450 Return the current process id.
451
452 The function is a stub on WASI, see :ref:`wasm-availability` for more
453 information.
454
455 .. function:: getppid()
456
457 .. index:: single: process; id of parent
458
459 Return the parent's process id. When the parent process has exited, on Unix
460 the id returned is the one of the init process (1), on Windows it is still
461 the same id, which may be already reused by another process.
462
463 .. availability:: Unix, Windows, not WASI.
464
465 .. versionchanged:: 3.2
466 Added support for Windows.
467
468
469 .. function:: getpriority(which, who)
470
471 .. index:: single: process; scheduling priority
472
473 Get program scheduling priority. The value *which* is one of
474 :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
475 is interpreted relative to *which* (a process identifier for
476 :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
477 user ID for :const:`PRIO_USER`). A zero value for *who* denotes
478 (respectively) the calling process, the process group of the calling process,
479 or the real user ID of the calling process.
480
481 .. availability:: Unix, not WASI.
482
483 .. versionadded:: 3.3
484
485
486 .. data:: PRIO_PROCESS
487 PRIO_PGRP
488 PRIO_USER
489
490 Parameters for the :func:`getpriority` and :func:`setpriority` functions.
491
492 .. availability:: Unix, not WASI.
493
494 .. versionadded:: 3.3
495
496
497 .. data:: PRIO_DARWIN_THREAD
498 PRIO_DARWIN_PROCESS
499 PRIO_DARWIN_BG
500 PRIO_DARWIN_NONUI
501
502 Parameters for the :func:`getpriority` and :func:`setpriority` functions.
503
504 .. availability:: macOS
505
506 .. versionadded:: 3.12
507
508 .. function:: getresuid()
509
510 Return a tuple (ruid, euid, suid) denoting the current process's
511 real, effective, and saved user ids.
512
513 .. availability:: Unix, not WASI.
514
515 .. versionadded:: 3.2
516
517
518 .. function:: getresgid()
519
520 Return a tuple (rgid, egid, sgid) denoting the current process's
521 real, effective, and saved group ids.
522
523 .. availability:: Unix, not WASI.
524
525 .. versionadded:: 3.2
526
527
528 .. function:: getuid()
529
530 .. index:: single: user; id
531
532 Return the current process's real user id.
533
534 .. availability:: Unix.
535
536 The function is a stub on WASI, see :ref:`wasm-availability` for more
537 information.
538
539
540 .. function:: initgroups(username, gid, /)
541
542 Call the system ``initgroups()`` to initialize the group access list with all of
543 the groups of which the specified username is a member, plus the specified
544 group id.
545
546 .. availability:: Unix, not WASI, not Android.
547
548 .. versionadded:: 3.2
549
550
551 .. function:: putenv(key, value, /)
552
553 .. index:: single: environment variables; setting
554
555 Set the environment variable named *key* to the string *value*. Such
556 changes to the environment affect subprocesses started with :func:`os.system`,
557 :func:`popen` or :func:`fork` and :func:`execv`.
558
559 Assignments to items in :data:`os.environ` are automatically translated into
560 corresponding calls to :func:`putenv`; however, calls to :func:`putenv`
561 don't update :data:`os.environ`, so it is actually preferable to assign to items
562 of :data:`os.environ`. This also applies to :func:`getenv` and :func:`getenvb`, which
563 respectively use :data:`os.environ` and :data:`os.environb` in their implementations.
564
565 .. note::
566
567 On some platforms, including FreeBSD and macOS, setting ``environ`` may
568 cause memory leaks. Refer to the system documentation for :c:func:`!putenv`.
569
570 .. audit-event:: os.putenv key,value os.putenv
571
572 .. versionchanged:: 3.9
573 The function is now always available.
574
575
576 .. function:: setegid(egid, /)
577
578 Set the current process's effective group id.
579
580 .. availability:: Unix, not WASI, not Android.
581
582
583 .. function:: seteuid(euid, /)
584
585 Set the current process's effective user id.
586
587 .. availability:: Unix, not WASI, not Android.
588
589
590 .. function:: setgid(gid, /)
591
592 Set the current process' group id.
593
594 .. availability:: Unix, not WASI, not Android.
595
596
597 .. function:: setgroups(groups, /)
598
599 Set the list of supplemental group ids associated with the current process to
600 *groups*. *groups* must be a sequence, and each element must be an integer
601 identifying a group. This operation is typically available only to the superuser.
602
603 .. availability:: Unix, not WASI.
604
605 .. note:: On macOS, the length of *groups* may not exceed the
606 system-defined maximum number of effective group ids, typically 16.
607 See the documentation for :func:`getgroups` for cases where it may not
608 return the same group list set by calling setgroups().
609
610 .. function:: setns(fd, nstype=0)
611
612 Reassociate the current thread with a Linux namespace.
613 See the :manpage:`setns(2)` and :manpage:`namespaces(7)` man pages for more
614 details.
615
616 If *fd* refers to a :file:`/proc/{pid}/ns/` link, ``setns()`` reassociates the
617 calling thread with the namespace associated with that link,
618 and *nstype* may be set to one of the
619 :ref:`CLONE_NEW* constants <os-unshare-clone-flags>`
620 to impose constraints on the operation
621 (``0`` means no constraints).
622
623 Since Linux 5.8, *fd* may refer to a PID file descriptor obtained from
624 :func:`~os.pidfd_open`. In this case, ``setns()`` reassociates the calling thread
625 into one or more of the same namespaces as the thread referred to by *fd*.
626 This is subject to any constraints imposed by *nstype*,
627 which is a bit mask combining one or more of the
628 :ref:`CLONE_NEW* constants <os-unshare-clone-flags>`,
629 e.g. ``setns(fd, os.CLONE_NEWUTS | os.CLONE_NEWPID)``.
630 The caller's memberships in unspecified namespaces are left unchanged.
631
632 *fd* can be any object with a :meth:`~io.IOBase.fileno` method, or a raw file descriptor.
633
634 This example reassociates the thread with the ``init`` process's network namespace::
635
636 fd = os.open("/proc/1/ns/net", os.O_RDONLY)
637 os.setns(fd, os.CLONE_NEWNET)
638 os.close(fd)
639
640 .. availability:: Linux >= 3.0 with glibc >= 2.14.
641
642 .. versionadded:: 3.12
643
644 .. seealso::
645
646 The :func:`~os.unshare` function.
647
648 .. function:: setpgrp()
649
650 Call the system call :c:func:`!setpgrp` or ``setpgrp(0, 0)`` depending on
651 which version is implemented (if any). See the Unix manual for the semantics.
652
653 .. availability:: Unix, not WASI.
654
655
656 .. function:: setpgid(pid, pgrp, /)
657
658 Call the system call :c:func:`!setpgid` to set the process group id of the
659 process with id *pid* to the process group with id *pgrp*. See the Unix manual
660 for the semantics.
661
662 .. availability:: Unix, not WASI.
663
664
665 .. function:: setpriority(which, who, priority)
666
667 .. index:: single: process; scheduling priority
668
669 Set program scheduling priority. The value *which* is one of
670 :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
671 is interpreted relative to *which* (a process identifier for
672 :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
673 user ID for :const:`PRIO_USER`). A zero value for *who* denotes
674 (respectively) the calling process, the process group of the calling process,
675 or the real user ID of the calling process.
676 *priority* is a value in the range -20 to 19. The default priority is 0;
677 lower priorities cause more favorable scheduling.
678
679 .. availability:: Unix, not WASI.
680
681 .. versionadded:: 3.3
682
683
684 .. function:: setregid(rgid, egid, /)
685
686 Set the current process's real and effective group ids.
687
688 .. availability:: Unix, not WASI, not Android.
689
690
691 .. function:: setresgid(rgid, egid, sgid, /)
692
693 Set the current process's real, effective, and saved group ids.
694
695 .. availability:: Unix, not WASI, not Android.
696
697 .. versionadded:: 3.2
698
699
700 .. function:: setresuid(ruid, euid, suid, /)
701
702 Set the current process's real, effective, and saved user ids.
703
704 .. availability:: Unix, not WASI, not Android.
705
706 .. versionadded:: 3.2
707
708
709 .. function:: setreuid(ruid, euid, /)
710
711 Set the current process's real and effective user ids.
712
713 .. availability:: Unix, not WASI, not Android.
714
715
716 .. function:: getsid(pid, /)
717
718 Call the system call :c:func:`!getsid`. See the Unix manual for the semantics.
719
720 .. availability:: Unix, not WASI.
721
722
723 .. function:: setsid()
724
725 Call the system call :c:func:`!setsid`. See the Unix manual for the semantics.
726
727 .. availability:: Unix, not WASI.
728
729
730 .. function:: setuid(uid, /)
731
732 .. index:: single: user; id, setting
733
734 Set the current process's user id.
735
736 .. availability:: Unix, not WASI, not Android.
737
738
739 .. placed in this section since it relates to errno.... a little weak
740 .. function:: strerror(code, /)
741
742 Return the error message corresponding to the error code in *code*.
743 On platforms where :c:func:`!strerror` returns ``NULL`` when given an unknown
744 error number, :exc:`ValueError` is raised.
745
746
747 .. data:: supports_bytes_environ
748
749 ``True`` if the native OS type of the environment is bytes (eg. ``False`` on
750 Windows).
751
752 .. versionadded:: 3.2
753
754
755 .. function:: umask(mask, /)
756
757 Set the current numeric umask and return the previous umask.
758
759 The function is a stub on WASI, see :ref:`wasm-availability` for more
760 information.
761
762
763 .. function:: uname()
764
765 .. index::
766 single: gethostname() (in module socket)
767 single: gethostbyaddr() (in module socket)
768
769 Returns information identifying the current operating system.
770 The return value is an object with five attributes:
771
772 * :attr:`sysname` - operating system name
773 * :attr:`nodename` - name of machine on network (implementation-defined)
774 * :attr:`release` - operating system release
775 * :attr:`version` - operating system version
776 * :attr:`machine` - hardware identifier
777
778 For backwards compatibility, this object is also iterable, behaving
779 like a five-tuple containing :attr:`sysname`, :attr:`nodename`,
780 :attr:`release`, :attr:`version`, and :attr:`machine`
781 in that order.
782
783 Some systems truncate :attr:`nodename` to 8 characters or to the
784 leading component; a better way to get the hostname is
785 :func:`socket.gethostname` or even
786 ``socket.gethostbyaddr(socket.gethostname())``.
787
788 On macOS, iOS and Android, this returns the *kernel* name and version (i.e.,
789 ``'Darwin'`` on macOS and iOS; ``'Linux'`` on Android). :func:`platform.uname`
790 can be used to get the user-facing operating system name and version on iOS and
791 Android.
792
793 .. availability:: Unix.
794
795 .. versionchanged:: 3.3
796 Return type changed from a tuple to a tuple-like object
797 with named attributes.
798
799
800 .. function:: unsetenv(key, /)
801
802 .. index:: single: environment variables; deleting
803
804 Unset (delete) the environment variable named *key*. Such changes to the
805 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
806 :func:`fork` and :func:`execv`.
807
808 Deletion of items in :data:`os.environ` is automatically translated into a
809 corresponding call to :func:`unsetenv`; however, calls to :func:`unsetenv`
810 don't update :data:`os.environ`, so it is actually preferable to delete items of
811 :data:`os.environ`.
812
813 .. audit-event:: os.unsetenv key os.unsetenv
814
815 .. versionchanged:: 3.9
816 The function is now always available and is also available on Windows.
817
818
819 .. function:: unshare(flags)
820
821 Disassociate parts of the process execution context, and move them into a
822 newly created namespace.
823 See the :manpage:`unshare(2)`
824 man page for more details.
825 The *flags* argument is a bit mask, combining zero or more of the
826 :ref:`CLONE_* constants <os-unshare-clone-flags>`,
827 that specifies which parts of the execution context should be
828 unshared from their existing associations and moved to a new namespace.
829 If the *flags* argument is ``0``, no changes are made to the calling process's
830 execution context.
831
832 .. availability:: Linux >= 2.6.16.
833
834 .. versionadded:: 3.12
835
836 .. seealso::
837
838 The :func:`~os.setns` function.
839
840 .. _os-unshare-clone-flags:
841
842 Flags to the :func:`unshare` function, if the implementation supports them.
843 See :manpage:`unshare(2)` in the Linux manual
844 for their exact effect and availability.
845
846 .. data:: CLONE_FILES
847 CLONE_FS
848 CLONE_NEWCGROUP
849 CLONE_NEWIPC
850 CLONE_NEWNET
851 CLONE_NEWNS
852 CLONE_NEWPID
853 CLONE_NEWTIME
854 CLONE_NEWUSER
855 CLONE_NEWUTS
856 CLONE_SIGHAND
857 CLONE_SYSVSEM
858 CLONE_THREAD
859 CLONE_VM
860
861
862 .. _os-newstreams:
863
864 File Object Creation
865 --------------------
866
867 These functions create new :term:`file objects <file object>`. (See also
868 :func:`~os.open` for opening file descriptors.)
869
870
871 .. function:: fdopen(fd, *args, **kwargs)
872
873 Return an open file object connected to the file descriptor *fd*. This is an
874 alias of the :func:`open` built-in function and accepts the same arguments.
875 The only difference is that the first argument of :func:`fdopen` must always
876 be an integer.
877
878
879 .. _os-fd-ops:
880
881 File Descriptor Operations
882 --------------------------
883
884 These functions operate on I/O streams referenced using file descriptors.
885
886 File descriptors are small integers corresponding to a file that has been opened
887 by the current process. For example, standard input is usually file descriptor
888 0, standard output is 1, and standard error is 2. Further files opened by a
889 process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
890 is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
891 by file descriptors.
892
893 The :meth:`~io.IOBase.fileno` method can be used to obtain the file descriptor
894 associated with a :term:`file object` when required. Note that using the file
895 descriptor directly will bypass the file object methods, ignoring aspects such
896 as internal buffering of data.
897
898
899 .. function:: close(fd)
900
901 Close file descriptor *fd*.
902
903 .. note::
904
905 This function is intended for low-level I/O and must be applied to a file
906 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
907 object" returned by the built-in function :func:`open` or by :func:`popen` or
908 :func:`fdopen`, use its :meth:`~io.IOBase.close` method.
909
910
911 .. function:: closerange(fd_low, fd_high, /)
912
913 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
914 ignoring errors. Equivalent to (but much faster than)::
915
916 for fd in range(fd_low, fd_high):
917 try:
918 os.close(fd)
919 except OSError:
920 pass
921
922
923 .. function:: copy_file_range(src, dst, count, offset_src=None, offset_dst=None)
924
925 Copy *count* bytes from file descriptor *src*, starting from offset
926 *offset_src*, to file descriptor *dst*, starting from offset *offset_dst*.
927 If *offset_src* is ``None``, then *src* is read from the current position;
928 respectively for *offset_dst*.
929
930 In Linux kernel older than 5.3, the files pointed to by *src* and *dst*
931 must reside in the same filesystem, otherwise an :exc:`OSError` is
932 raised with :attr:`~OSError.errno` set to :const:`errno.EXDEV`.
933
934 This copy is done without the additional cost of transferring data
935 from the kernel to user space and then back into the kernel. Additionally,
936 some filesystems could implement extra optimizations, such as the use of
937 reflinks (i.e., two or more inodes that share pointers to the same
938 copy-on-write disk blocks; supported file systems include btrfs and XFS)
939 and server-side copy (in the case of NFS).
940
941 The function copies bytes between two file descriptors. Text options, like
942 the encoding and the line ending, are ignored.
943
944 The return value is the amount of bytes copied. This could be less than the
945 amount requested.
946
947 .. note::
948
949 On Linux, :func:`os.copy_file_range` should not be used for copying a
950 range of a pseudo file from a special filesystem like procfs and sysfs.
951 It will always copy no bytes and return 0 as if the file was empty
952 because of a known Linux kernel issue.
953
954 .. availability:: Linux >= 4.5 with glibc >= 2.27.
955
956 .. versionadded:: 3.8
957
958
959 .. function:: device_encoding(fd)
960
961 Return a string describing the encoding of the device associated with *fd*
962 if it is connected to a terminal; else return :const:`None`.
963
964 On Unix, if the :ref:`Python UTF-8 Mode <utf8-mode>` is enabled, return
965 ``'UTF-8'`` rather than the device encoding.
966
967 .. versionchanged:: 3.10
968 On Unix, the function now implements the Python UTF-8 Mode.
969
970
971 .. function:: dup(fd, /)
972
973 Return a duplicate of file descriptor *fd*. The new file descriptor is
974 :ref:`non-inheritable <fd_inheritance>`.
975
976 On Windows, when duplicating a standard stream (0: stdin, 1: stdout,
977 2: stderr), the new file descriptor is :ref:`inheritable
978 <fd_inheritance>`.
979
980 .. availability:: not WASI.
981
982 .. versionchanged:: 3.4
983 The new file descriptor is now non-inheritable.
984
985
986 .. function:: dup2(fd, fd2, inheritable=True)
987
988 Duplicate file descriptor *fd* to *fd2*, closing the latter first if
989 necessary. Return *fd2*. The new file descriptor is :ref:`inheritable
990 <fd_inheritance>` by default or non-inheritable if *inheritable*
991 is ``False``.
992
993 .. availability:: not WASI.
994
995 .. versionchanged:: 3.4
996 Add the optional *inheritable* parameter.
997
998 .. versionchanged:: 3.7
999 Return *fd2* on success. Previously, ``None`` was always returned.
1000
1001
1002 .. function:: fchmod(fd, mode)
1003
1004 Change the mode of the file given by *fd* to the numeric *mode*. See the
1005 docs for :func:`chmod` for possible values of *mode*. As of Python 3.3, this
1006 is equivalent to ``os.chmod(fd, mode)``.
1007
1008 .. audit-event:: os.chmod path,mode,dir_fd os.fchmod
1009
1010 .. availability:: Unix, Windows.
1011
1012 The function is limited on WASI, see :ref:`wasm-availability` for more
1013 information.
1014
1015 .. versionchanged:: 3.13
1016 Added support on Windows.
1017
1018
1019 .. function:: fchown(fd, uid, gid)
1020
1021 Change the owner and group id of the file given by *fd* to the numeric *uid*
1022 and *gid*. To leave one of the ids unchanged, set it to -1. See
1023 :func:`chown`. As of Python 3.3, this is equivalent to ``os.chown(fd, uid,
1024 gid)``.
1025
1026 .. audit-event:: os.chown path,uid,gid,dir_fd os.fchown
1027
1028 .. availability:: Unix.
1029
1030 The function is limited on WASI, see :ref:`wasm-availability` for more
1031 information.
1032
1033
1034 .. function:: fdatasync(fd)
1035
1036 Force write of file with filedescriptor *fd* to disk. Does not force update of
1037 metadata.
1038
1039 .. availability:: Unix.
1040
1041 .. note::
1042 This function is not available on MacOS.
1043
1044
1045 .. function:: fpathconf(fd, name, /)
1046
1047 Return system configuration information relevant to an open file. *name*
1048 specifies the configuration value to retrieve; it may be a string which is the
1049 name of a defined system value; these names are specified in a number of
1050 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1051 additional names as well. The names known to the host operating system are
1052 given in the ``pathconf_names`` dictionary. For configuration variables not
1053 included in that mapping, passing an integer for *name* is also accepted.
1054
1055 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1056 specific value for *name* is not supported by the host system, even if it is
1057 included in ``pathconf_names``, an :exc:`OSError` is raised with
1058 :const:`errno.EINVAL` for the error number.
1059
1060 As of Python 3.3, this is equivalent to ``os.pathconf(fd, name)``.
1061
1062 .. availability:: Unix.
1063
1064
1065 .. function:: fstat(fd)
1066
1067 Get the status of the file descriptor *fd*. Return a :class:`stat_result`
1068 object.
1069
1070 As of Python 3.3, this is equivalent to ``os.stat(fd)``.
1071
1072 .. seealso::
1073
1074 The :func:`.stat` function.
1075
1076
1077 .. function:: fstatvfs(fd, /)
1078
1079 Return information about the filesystem containing the file associated with
1080 file descriptor *fd*, like :func:`statvfs`. As of Python 3.3, this is
1081 equivalent to ``os.statvfs(fd)``.
1082
1083 .. availability:: Unix.
1084
1085
1086 .. function:: fsync(fd)
1087
1088 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
1089 native :c:func:`!fsync` function; on Windows, the MS :c:func:`!_commit` function.
1090
1091 If you're starting with a buffered Python :term:`file object` *f*, first do
1092 ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal
1093 buffers associated with *f* are written to disk.
1094
1095 .. availability:: Unix, Windows.
1096
1097
1098 .. function:: ftruncate(fd, length, /)
1099
1100 Truncate the file corresponding to file descriptor *fd*, so that it is at
1101 most *length* bytes in size. As of Python 3.3, this is equivalent to
1102 ``os.truncate(fd, length)``.
1103
1104 .. audit-event:: os.truncate fd,length os.ftruncate
1105
1106 .. availability:: Unix, Windows.
1107
1108 .. versionchanged:: 3.5
1109 Added support for Windows
1110
1111
1112 .. function:: get_blocking(fd, /)
1113
1114 Get the blocking mode of the file descriptor: ``False`` if the
1115 :data:`O_NONBLOCK` flag is set, ``True`` if the flag is cleared.
1116
1117 See also :func:`set_blocking` and :meth:`socket.socket.setblocking`.
1118
1119 .. availability:: Unix, Windows.
1120
1121 The function is limited on WASI, see :ref:`wasm-availability` for more
1122 information.
1123
1124 On Windows, this function is limited to pipes.
1125
1126 .. versionadded:: 3.5
1127
1128 .. versionchanged:: 3.12
1129 Added support for pipes on Windows.
1130
1131
1132 .. function:: grantpt(fd, /)
1133
1134 Grant access to the slave pseudo-terminal device associated with the
1135 master pseudo-terminal device to which the file descriptor *fd* refers.
1136 The file descriptor *fd* is not closed upon failure.
1137
1138 Calls the C standard library function :c:func:`grantpt`.
1139
1140 .. availability:: Unix, not WASI.
1141
1142 .. versionadded:: 3.13
1143
1144
1145 .. function:: isatty(fd, /)
1146
1147 Return ``True`` if the file descriptor *fd* is open and connected to a
1148 tty(-like) device, else ``False``.
1149
1150
1151 .. function:: lockf(fd, cmd, len, /)
1152
1153 Apply, test or remove a POSIX lock on an open file descriptor.
1154 *fd* is an open file descriptor.
1155 *cmd* specifies the command to use - one of :data:`F_LOCK`, :data:`F_TLOCK`,
1156 :data:`F_ULOCK` or :data:`F_TEST`.
1157 *len* specifies the section of the file to lock.
1158
1159 .. audit-event:: os.lockf fd,cmd,len os.lockf
1160
1161 .. availability:: Unix.
1162
1163 .. versionadded:: 3.3
1164
1165
1166 .. data:: F_LOCK
1167 F_TLOCK
1168 F_ULOCK
1169 F_TEST
1170
1171 Flags that specify what action :func:`lockf` will take.
1172
1173 .. availability:: Unix.
1174
1175 .. versionadded:: 3.3
1176
1177
1178 .. function:: login_tty(fd, /)
1179
1180 Prepare the tty of which fd is a file descriptor for a new login session.
1181 Make the calling process a session leader; make the tty the controlling tty,
1182 the stdin, the stdout, and the stderr of the calling process; close fd.
1183
1184 .. availability:: Unix, not WASI.
1185
1186 .. versionadded:: 3.11
1187
1188
1189 .. function:: lseek(fd, pos, whence, /)
1190
1191 Set the current position of file descriptor *fd* to position *pos*, modified
1192 by *whence*, and return the new position in bytes relative to
1193 the start of the file.
1194 Valid values for *whence* are:
1195
1196 * :const:`SEEK_SET` or ``0`` -- set *pos* relative to the beginning of the file
1197 * :const:`SEEK_CUR` or ``1`` -- set *pos* relative to the current file position
1198 * :const:`SEEK_END` or ``2`` -- set *pos* relative to the end of the file
1199 * :const:`SEEK_HOLE` -- set *pos* to the next data location, relative to *pos*
1200 * :const:`SEEK_DATA` -- set *pos* to the next data hole, relative to *pos*
1201
1202 .. versionchanged:: 3.3
1203
1204 Add support for :const:`!SEEK_HOLE` and :const:`!SEEK_DATA`.
1205
1206
1207 .. data:: SEEK_SET
1208 SEEK_CUR
1209 SEEK_END
1210
1211 Parameters to the :func:`lseek` function and the :meth:`~io.IOBase.seek`
1212 method on :term:`file-like objects <file object>`,
1213 for whence to adjust the file position indicator.
1214
1215 :const:`SEEK_SET`
1216 Adjust the file position relative to the beginning of the file.
1217 :const:`SEEK_CUR`
1218 Adjust the file position relative to the current file position.
1219 :const:`SEEK_END`
1220 Adjust the file position relative to the end of the file.
1221
1222 Their values are 0, 1, and 2, respectively.
1223
1224
1225 .. data:: SEEK_HOLE
1226 SEEK_DATA
1227
1228 Parameters to the :func:`lseek` function and the :meth:`~io.IOBase.seek`
1229 method on :term:`file-like objects <file object>`,
1230 for seeking file data and holes on sparsely allocated files.
1231
1232 :data:`!SEEK_DATA`
1233 Adjust the file offset to the next location containing data,
1234 relative to the seek position.
1235
1236 :data:`!SEEK_HOLE`
1237 Adjust the file offset to the next location containing a hole,
1238 relative to the seek position.
1239 A hole is defined as a sequence of zeros.
1240
1241 .. note::
1242
1243 These operations only make sense for filesystems that support them.
1244
1245 .. availability:: Linux >= 3.1, macOS, Unix
1246
1247 .. versionadded:: 3.3
1248
1249
1250 .. function:: open(path, flags, mode=0o777, *, dir_fd=None)
1251
1252 Open the file *path* and set various flags according to *flags* and possibly
1253 its mode according to *mode*. When computing *mode*, the current umask value
1254 is first masked out. Return the file descriptor for the newly opened file.
1255 The new file descriptor is :ref:`non-inheritable <fd_inheritance>`.
1256
1257 For a description of the flag and mode values, see the C run-time documentation;
1258 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
1259 the :mod:`os` module. In particular, on Windows adding
1260 :const:`O_BINARY` is needed to open files in binary mode.
1261
1262 This function can support :ref:`paths relative to directory descriptors
1263 <dir_fd>` with the *dir_fd* parameter.
1264
1265 .. audit-event:: open path,mode,flags os.open
1266
1267 .. versionchanged:: 3.4
1268 The new file descriptor is now non-inheritable.
1269
1270 .. note::
1271
1272 This function is intended for low-level I/O. For normal usage, use the
1273 built-in function :func:`open`, which returns a :term:`file object` with
1274 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
1275 wrap a file descriptor in a file object, use :func:`fdopen`.
1276
1277 .. versionchanged:: 3.3
1278 Added the *dir_fd* parameter.
1279
1280 .. versionchanged:: 3.5
1281 If the system call is interrupted and the signal handler does not raise an
1282 exception, the function now retries the system call instead of raising an
1283 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1284
1285 .. versionchanged:: 3.6
1286 Accepts a :term:`path-like object`.
1287
1288 The following constants are options for the *flags* parameter to the
1289 :func:`~os.open` function. They can be combined using the bitwise OR operator
1290 ``|``. Some of them are not available on all platforms. For descriptions of
1291 their availability and use, consult the :manpage:`open(2)` manual page on Unix
1292 or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
1293
1294
1295 .. data:: O_RDONLY
1296 O_WRONLY
1297 O_RDWR
1298 O_APPEND
1299 O_CREAT
1300 O_EXCL
1301 O_TRUNC
1302
1303 The above constants are available on Unix and Windows.
1304
1305
1306 .. data:: O_DSYNC
1307 O_RSYNC
1308 O_SYNC
1309 O_NDELAY
1310 O_NONBLOCK
1311 O_NOCTTY
1312 O_CLOEXEC
1313
1314 The above constants are only available on Unix.
1315
1316 .. versionchanged:: 3.3
1317 Add :data:`O_CLOEXEC` constant.
1318
1319 .. data:: O_BINARY
1320 O_NOINHERIT
1321 O_SHORT_LIVED
1322 O_TEMPORARY
1323 O_RANDOM
1324 O_SEQUENTIAL
1325 O_TEXT
1326
1327 The above constants are only available on Windows.
1328
1329 .. data:: O_EVTONLY
1330 O_FSYNC
1331 O_SYMLINK
1332 O_NOFOLLOW_ANY
1333
1334 The above constants are only available on macOS.
1335
1336 .. versionchanged:: 3.10
1337 Add :data:`O_EVTONLY`, :data:`O_FSYNC`, :data:`O_SYMLINK`
1338 and :data:`O_NOFOLLOW_ANY` constants.
1339
1340 .. data:: O_ASYNC
1341 O_DIRECT
1342 O_DIRECTORY
1343 O_NOFOLLOW
1344 O_NOATIME
1345 O_PATH
1346 O_TMPFILE
1347 O_SHLOCK
1348 O_EXLOCK
1349
1350 The above constants are extensions and not present if they are not defined by
1351 the C library.
1352
1353 .. versionchanged:: 3.4
1354 Add :data:`O_PATH` on systems that support it.
1355 Add :data:`O_TMPFILE`, only available on Linux Kernel 3.11
1356 or newer.
1357
1358
1359 .. function:: openpty()
1360
1361 .. index:: pair: module; pty
1362
1363 Open a new pseudo-terminal pair. Return a pair of file descriptors
1364 ``(master, slave)`` for the pty and the tty, respectively. The new file
1365 descriptors are :ref:`non-inheritable <fd_inheritance>`. For a (slightly) more
1366 portable approach, use the :mod:`pty` module.
1367
1368 .. availability:: Unix, not WASI.
1369
1370 .. versionchanged:: 3.4
1371 The new file descriptors are now non-inheritable.
1372
1373
1374 .. function:: pipe()
1375
1376 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for
1377 reading and writing, respectively. The new file descriptor is
1378 :ref:`non-inheritable <fd_inheritance>`.
1379
1380 .. availability:: Unix, Windows.
1381
1382 .. versionchanged:: 3.4
1383 The new file descriptors are now non-inheritable.
1384
1385
1386 .. function:: pipe2(flags, /)
1387
1388 Create a pipe with *flags* set atomically.
1389 *flags* can be constructed by ORing together one or more of these values:
1390 :data:`O_NONBLOCK`, :data:`O_CLOEXEC`.
1391 Return a pair of file descriptors ``(r, w)`` usable for reading and writing,
1392 respectively.
1393
1394 .. availability:: Unix, not WASI.
1395
1396 .. versionadded:: 3.3
1397
1398
1399 .. function:: posix_fallocate(fd, offset, len, /)
1400
1401 Ensures that enough disk space is allocated for the file specified by *fd*
1402 starting from *offset* and continuing for *len* bytes.
1403
1404 .. availability:: Unix.
1405
1406 .. versionadded:: 3.3
1407
1408
1409 .. function:: posix_fadvise(fd, offset, len, advice, /)
1410
1411 Announces an intention to access data in a specific pattern thus allowing
1412 the kernel to make optimizations.
1413 The advice applies to the region of the file specified by *fd* starting at
1414 *offset* and continuing for *len* bytes.
1415 *advice* is one of :data:`POSIX_FADV_NORMAL`, :data:`POSIX_FADV_SEQUENTIAL`,
1416 :data:`POSIX_FADV_RANDOM`, :data:`POSIX_FADV_NOREUSE`,
1417 :data:`POSIX_FADV_WILLNEED` or :data:`POSIX_FADV_DONTNEED`.
1418
1419 .. availability:: Unix.
1420
1421 .. versionadded:: 3.3
1422
1423
1424 .. data:: POSIX_FADV_NORMAL
1425 POSIX_FADV_SEQUENTIAL
1426 POSIX_FADV_RANDOM
1427 POSIX_FADV_NOREUSE
1428 POSIX_FADV_WILLNEED
1429 POSIX_FADV_DONTNEED
1430
1431 Flags that can be used in *advice* in :func:`posix_fadvise` that specify
1432 the access pattern that is likely to be used.
1433
1434 .. availability:: Unix.
1435
1436 .. versionadded:: 3.3
1437
1438
1439 .. function:: pread(fd, n, offset, /)
1440
1441 Read at most *n* bytes from file descriptor *fd* at a position of *offset*,
1442 leaving the file offset unchanged.
1443
1444 Return a bytestring containing the bytes read. If the end of the file
1445 referred to by *fd* has been reached, an empty bytes object is returned.
1446
1447 .. availability:: Unix.
1448
1449 .. versionadded:: 3.3
1450
1451
1452 .. function:: posix_openpt(oflag, /)
1453
1454 Open and return a file descriptor for a master pseudo-terminal device.
1455
1456 Calls the C standard library function :c:func:`posix_openpt`. The *oflag*
1457 argument is used to set file status flags and file access modes as
1458 specified in the manual page of :c:func:`posix_openpt` of your system.
1459
1460 The returned file descriptor is :ref:`non-inheritable <fd_inheritance>`.
1461 If the value :data:`O_CLOEXEC` is available on the system, it is added to
1462 *oflag*.
1463
1464 .. availability:: Unix, not WASI.
1465
1466 .. versionadded:: 3.13
1467
1468
1469 .. function:: preadv(fd, buffers, offset, flags=0, /)
1470
1471 Read from a file descriptor *fd* at a position of *offset* into mutable
1472 :term:`bytes-like objects <bytes-like object>` *buffers*, leaving the file
1473 offset unchanged. Transfer data into each buffer until it is full and then
1474 move on to the next buffer in the sequence to hold the rest of the data.
1475
1476 The flags argument contains a bitwise OR of zero or more of the following
1477 flags:
1478
1479 - :data:`RWF_HIPRI`
1480 - :data:`RWF_NOWAIT`
1481
1482 Return the total number of bytes actually read which can be less than the
1483 total capacity of all the objects.
1484
1485 The operating system may set a limit (:func:`sysconf` value
1486 ``'SC_IOV_MAX'``) on the number of buffers that can be used.
1487
1488 Combine the functionality of :func:`os.readv` and :func:`os.pread`.
1489
1490 .. availability:: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.
1491
1492 Using flags requires Linux >= 4.6.
1493
1494 .. versionadded:: 3.7
1495
1496
1497 .. data:: RWF_NOWAIT
1498
1499 Do not wait for data which is not immediately available. If this flag is
1500 specified, the system call will return instantly if it would have to read
1501 data from the backing storage or wait for a lock.
1502
1503 If some data was successfully read, it will return the number of bytes read.
1504 If no bytes were read, it will return ``-1`` and set errno to
1505 :const:`errno.EAGAIN`.
1506
1507 .. availability:: Linux >= 4.14.
1508
1509 .. versionadded:: 3.7
1510
1511
1512 .. data:: RWF_HIPRI
1513
1514 High priority read/write. Allows block-based filesystems to use polling
1515 of the device, which provides lower latency, but may use additional
1516 resources.
1517
1518 Currently, on Linux, this feature is usable only on a file descriptor opened
1519 using the :data:`O_DIRECT` flag.
1520
1521 .. availability:: Linux >= 4.6.
1522
1523 .. versionadded:: 3.7
1524
1525
1526 .. function:: ptsname(fd, /)
1527
1528 Return the name of the slave pseudo-terminal device associated with the
1529 master pseudo-terminal device to which the file descriptor *fd* refers.
1530 The file descriptor *fd* is not closed upon failure.
1531
1532 Calls the reentrant C standard library function :c:func:`ptsname_r` if
1533 it is available; otherwise, the C standard library function
1534 :c:func:`ptsname`, which is not guaranteed to be thread-safe, is called.
1535
1536 .. availability:: Unix, not WASI.
1537
1538 .. versionadded:: 3.13
1539
1540
1541 .. function:: pwrite(fd, str, offset, /)
1542
1543 Write the bytestring in *str* to file descriptor *fd* at position of
1544 *offset*, leaving the file offset unchanged.
1545
1546 Return the number of bytes actually written.
1547
1548 .. availability:: Unix.
1549
1550 .. versionadded:: 3.3
1551
1552
1553 .. function:: pwritev(fd, buffers, offset, flags=0, /)
1554
1555 Write the *buffers* contents to file descriptor *fd* at an offset *offset*,
1556 leaving the file offset unchanged. *buffers* must be a sequence of
1557 :term:`bytes-like objects <bytes-like object>`. Buffers are processed in
1558 array order. Entire contents of the first buffer is written before
1559 proceeding to the second, and so on.
1560
1561 The flags argument contains a bitwise OR of zero or more of the following
1562 flags:
1563
1564 - :data:`RWF_DSYNC`
1565 - :data:`RWF_SYNC`
1566 - :data:`RWF_APPEND`
1567
1568 Return the total number of bytes actually written.
1569
1570 The operating system may set a limit (:func:`sysconf` value
1571 ``'SC_IOV_MAX'``) on the number of buffers that can be used.
1572
1573 Combine the functionality of :func:`os.writev` and :func:`os.pwrite`.
1574
1575 .. availability:: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.
1576
1577 Using flags requires Linux >= 4.6.
1578
1579 .. versionadded:: 3.7
1580
1581
1582 .. data:: RWF_DSYNC
1583
1584 Provide a per-write equivalent of the :data:`O_DSYNC` :func:`os.open` flag.
1585 This flag effect applies only to the data range written by the system call.
1586
1587 .. availability:: Linux >= 4.7.
1588
1589 .. versionadded:: 3.7
1590
1591
1592 .. data:: RWF_SYNC
1593
1594 Provide a per-write equivalent of the :data:`O_SYNC` :func:`os.open` flag.
1595 This flag effect applies only to the data range written by the system call.
1596
1597 .. availability:: Linux >= 4.7.
1598
1599 .. versionadded:: 3.7
1600
1601
1602 .. data:: RWF_APPEND
1603
1604 Provide a per-write equivalent of the :data:`O_APPEND` :func:`os.open`
1605 flag. This flag is meaningful only for :func:`os.pwritev`, and its
1606 effect applies only to the data range written by the system call. The
1607 *offset* argument does not affect the write operation; the data is always
1608 appended to the end of the file. However, if the *offset* argument is
1609 ``-1``, the current file *offset* is updated.
1610
1611 .. availability:: Linux >= 4.16.
1612
1613 .. versionadded:: 3.10
1614
1615
1616 .. function:: read(fd, n, /)
1617
1618 Read at most *n* bytes from file descriptor *fd*.
1619
1620 Return a bytestring containing the bytes read. If the end of the file
1621 referred to by *fd* has been reached, an empty bytes object is returned.
1622
1623 .. note::
1624
1625 This function is intended for low-level I/O and must be applied to a file
1626 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a
1627 "file object" returned by the built-in function :func:`open` or by
1628 :func:`popen` or :func:`fdopen`, or :data:`sys.stdin`, use its
1629 :meth:`~file.read` or :meth:`~file.readline` methods.
1630
1631 .. versionchanged:: 3.5
1632 If the system call is interrupted and the signal handler does not raise an
1633 exception, the function now retries the system call instead of raising an
1634 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1635
1636
1637 .. function:: sendfile(out_fd, in_fd, offset, count)
1638 sendfile(out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0)
1639
1640 Copy *count* bytes from file descriptor *in_fd* to file descriptor *out_fd*
1641 starting at *offset*.
1642 Return the number of bytes sent. When EOF is reached return ``0``.
1643
1644 The first function notation is supported by all platforms that define
1645 :func:`sendfile`.
1646
1647 On Linux, if *offset* is given as ``None``, the bytes are read from the
1648 current position of *in_fd* and the position of *in_fd* is updated.
1649
1650 The second case may be used on macOS and FreeBSD where *headers* and
1651 *trailers* are arbitrary sequences of buffers that are written before and
1652 after the data from *in_fd* is written. It returns the same as the first case.
1653
1654 On macOS and FreeBSD, a value of ``0`` for *count* specifies to send until
1655 the end of *in_fd* is reached.
1656
1657 All platforms support sockets as *out_fd* file descriptor, and some platforms
1658 allow other types (e.g. regular file, pipe) as well.
1659
1660 Cross-platform applications should not use *headers*, *trailers* and *flags*
1661 arguments.
1662
1663 .. availability:: Unix, not WASI.
1664
1665 .. note::
1666
1667 For a higher-level wrapper of :func:`sendfile`, see
1668 :meth:`socket.socket.sendfile`.
1669
1670 .. versionadded:: 3.3
1671
1672 .. versionchanged:: 3.9
1673 Parameters *out* and *in* was renamed to *out_fd* and *in_fd*.
1674
1675
1676 .. data:: SF_NODISKIO
1677 SF_MNOWAIT
1678 SF_SYNC
1679
1680 Parameters to the :func:`sendfile` function, if the implementation supports
1681 them.
1682
1683 .. availability:: Unix, not WASI.
1684
1685 .. versionadded:: 3.3
1686
1687 .. data:: SF_NOCACHE
1688
1689 Parameter to the :func:`sendfile` function, if the implementation supports
1690 it. The data won't be cached in the virtual memory and will be freed afterwards.
1691
1692 .. availability:: Unix, not WASI.
1693
1694 .. versionadded:: 3.11
1695
1696
1697 .. function:: set_blocking(fd, blocking, /)
1698
1699 Set the blocking mode of the specified file descriptor. Set the
1700 :data:`O_NONBLOCK` flag if blocking is ``False``, clear the flag otherwise.
1701
1702 See also :func:`get_blocking` and :meth:`socket.socket.setblocking`.
1703
1704 .. availability:: Unix, Windows.
1705
1706 The function is limited on WASI, see :ref:`wasm-availability` for more
1707 information.
1708
1709 On Windows, this function is limited to pipes.
1710
1711 .. versionadded:: 3.5
1712
1713 .. versionchanged:: 3.12
1714 Added support for pipes on Windows.
1715
1716
1717 .. function:: splice(src, dst, count, offset_src=None, offset_dst=None)
1718
1719 Transfer *count* bytes from file descriptor *src*, starting from offset
1720 *offset_src*, to file descriptor *dst*, starting from offset *offset_dst*.
1721 At least one of the file descriptors must refer to a pipe. If *offset_src*
1722 is ``None``, then *src* is read from the current position; respectively for
1723 *offset_dst*. The offset associated to the file descriptor that refers to a
1724 pipe must be ``None``. The files pointed to by *src* and *dst* must reside in
1725 the same filesystem, otherwise an :exc:`OSError` is raised with
1726 :attr:`~OSError.errno` set to :const:`errno.EXDEV`.
1727
1728 This copy is done without the additional cost of transferring data
1729 from the kernel to user space and then back into the kernel. Additionally,
1730 some filesystems could implement extra optimizations. The copy is done as if
1731 both files are opened as binary.
1732
1733 Upon successful completion, returns the number of bytes spliced to or from
1734 the pipe. A return value of 0 means end of input. If *src* refers to a
1735 pipe, then this means that there was no data to transfer, and it would not
1736 make sense to block because there are no writers connected to the write end
1737 of the pipe.
1738
1739 .. availability:: Linux >= 2.6.17 with glibc >= 2.5
1740
1741 .. versionadded:: 3.10
1742
1743
1744 .. data:: SPLICE_F_MOVE
1745 SPLICE_F_NONBLOCK
1746 SPLICE_F_MORE
1747
1748 .. versionadded:: 3.10
1749
1750 .. function:: readv(fd, buffers, /)
1751
1752 Read from a file descriptor *fd* into a number of mutable :term:`bytes-like
1753 objects <bytes-like object>` *buffers*. Transfer data into each buffer until
1754 it is full and then move on to the next buffer in the sequence to hold the
1755 rest of the data.
1756
1757 Return the total number of bytes actually read which can be less than the
1758 total capacity of all the objects.
1759
1760 The operating system may set a limit (:func:`sysconf` value
1761 ``'SC_IOV_MAX'``) on the number of buffers that can be used.
1762
1763 .. availability:: Unix.
1764
1765 .. versionadded:: 3.3
1766
1767
1768 .. function:: tcgetpgrp(fd, /)
1769
1770 Return the process group associated with the terminal given by *fd* (an open
1771 file descriptor as returned by :func:`os.open`).
1772
1773 .. availability:: Unix, not WASI.
1774
1775
1776 .. function:: tcsetpgrp(fd, pg, /)
1777
1778 Set the process group associated with the terminal given by *fd* (an open file
1779 descriptor as returned by :func:`os.open`) to *pg*.
1780
1781 .. availability:: Unix, not WASI.
1782
1783
1784 .. function:: ttyname(fd, /)
1785
1786 Return a string which specifies the terminal device associated with
1787 file descriptor *fd*. If *fd* is not associated with a terminal device, an
1788 exception is raised.
1789
1790 .. availability:: Unix.
1791
1792
1793 .. function:: unlockpt(fd, /)
1794
1795 Unlock the slave pseudo-terminal device associated with the master
1796 pseudo-terminal device to which the file descriptor *fd* refers.
1797 The file descriptor *fd* is not closed upon failure.
1798
1799 Calls the C standard library function :c:func:`unlockpt`.
1800
1801 .. availability:: Unix, not WASI.
1802
1803 .. versionadded:: 3.13
1804
1805
1806 .. function:: write(fd, str, /)
1807
1808 Write the bytestring in *str* to file descriptor *fd*.
1809
1810 Return the number of bytes actually written.
1811
1812 .. note::
1813
1814 This function is intended for low-level I/O and must be applied to a file
1815 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
1816 object" returned by the built-in function :func:`open` or by :func:`popen` or
1817 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
1818 :meth:`~file.write` method.
1819
1820 .. versionchanged:: 3.5
1821 If the system call is interrupted and the signal handler does not raise an
1822 exception, the function now retries the system call instead of raising an
1823 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1824
1825
1826 .. function:: writev(fd, buffers, /)
1827
1828 Write the contents of *buffers* to file descriptor *fd*. *buffers* must be
1829 a sequence of :term:`bytes-like objects <bytes-like object>`. Buffers are
1830 processed in array order. Entire contents of the first buffer is written
1831 before proceeding to the second, and so on.
1832
1833 Returns the total number of bytes actually written.
1834
1835 The operating system may set a limit (:func:`sysconf` value
1836 ``'SC_IOV_MAX'``) on the number of buffers that can be used.
1837
1838 .. availability:: Unix.
1839
1840 .. versionadded:: 3.3
1841
1842
1843 .. _terminal-size:
1844
1845 Querying the size of a terminal
1846 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1847
1848 .. versionadded:: 3.3
1849
1850 .. function:: get_terminal_size(fd=STDOUT_FILENO, /)
1851
1852 Return the size of the terminal window as ``(columns, lines)``,
1853 tuple of type :class:`terminal_size`.
1854
1855 The optional argument ``fd`` (default ``STDOUT_FILENO``, or standard
1856 output) specifies which file descriptor should be queried.
1857
1858 If the file descriptor is not connected to a terminal, an :exc:`OSError`
1859 is raised.
1860
1861 :func:`shutil.get_terminal_size` is the high-level function which
1862 should normally be used, ``os.get_terminal_size`` is the low-level
1863 implementation.
1864
1865 .. availability:: Unix, Windows.
1866
1867 .. class:: terminal_size
1868
1869 A subclass of tuple, holding ``(columns, lines)`` of the terminal window size.
1870
1871 .. attribute:: columns
1872
1873 Width of the terminal window in characters.
1874
1875 .. attribute:: lines
1876
1877 Height of the terminal window in characters.
1878
1879
1880 .. _fd_inheritance:
1881
1882 Inheritance of File Descriptors
1883 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1884
1885 .. versionadded:: 3.4
1886
1887 A file descriptor has an "inheritable" flag which indicates if the file descriptor
1888 can be inherited by child processes. Since Python 3.4, file descriptors
1889 created by Python are non-inheritable by default.
1890
1891 On UNIX, non-inheritable file descriptors are closed in child processes at the
1892 execution of a new program, other file descriptors are inherited. Note that
1893 non-inheritable file descriptors are still *inherited* by child processes on :func:`os.fork`.
1894
1895 On Windows, non-inheritable handles and file descriptors are closed in child
1896 processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout
1897 and stderr), which are always inherited. Using :func:`spawn\* <spawnl>` functions,
1898 all inheritable handles and all inheritable file descriptors are inherited.
1899 Using the :mod:`subprocess` module, all file descriptors except standard
1900 streams are closed, and inheritable handles are only inherited if the
1901 *close_fds* parameter is ``False``.
1902
1903 On WebAssembly platforms, the file descriptor cannot be modified.
1904
1905 .. function:: get_inheritable(fd, /)
1906
1907 Get the "inheritable" flag of the specified file descriptor (a boolean).
1908
1909 .. function:: set_inheritable(fd, inheritable, /)
1910
1911 Set the "inheritable" flag of the specified file descriptor.
1912
1913 .. function:: get_handle_inheritable(handle, /)
1914
1915 Get the "inheritable" flag of the specified handle (a boolean).
1916
1917 .. availability:: Windows.
1918
1919 .. function:: set_handle_inheritable(handle, inheritable, /)
1920
1921 Set the "inheritable" flag of the specified handle.
1922
1923 .. availability:: Windows.
1924
1925
1926 .. _os-file-dir:
1927
1928 Files and Directories
1929 ---------------------
1930
1931 On some Unix platforms, many of these functions support one or more of these
1932 features:
1933
1934 .. _path_fd:
1935
1936 * **specifying a file descriptor:**
1937 Normally the *path* argument provided to functions in the :mod:`os` module
1938 must be a string specifying a file path. However, some functions now
1939 alternatively accept an open file descriptor for their *path* argument.
1940 The function will then operate on the file referred to by the descriptor.
1941 For POSIX systems, Python will call the variant of the function prefixed
1942 with ``f`` (e.g. call ``fchdir`` instead of ``chdir``).
1943
1944 You can check whether or not *path* can be specified as a file descriptor
1945 for a particular function on your platform using :data:`os.supports_fd`.
1946 If this functionality is unavailable, using it will raise a
1947 :exc:`NotImplementedError`.
1948
1949 If the function also supports *dir_fd* or *follow_symlinks* arguments, it's
1950 an error to specify one of those when supplying *path* as a file descriptor.
1951
1952 .. _dir_fd:
1953
1954 * **paths relative to directory descriptors:** If *dir_fd* is not ``None``, it
1955 should be a file descriptor referring to a directory, and the path to operate
1956 on should be relative; path will then be relative to that directory. If the
1957 path is absolute, *dir_fd* is ignored. For POSIX systems, Python will call
1958 the variant of the function with an ``at`` suffix and possibly prefixed with
1959 ``f`` (e.g. call ``faccessat`` instead of ``access``).
1960
1961 You can check whether or not *dir_fd* is supported for a particular function
1962 on your platform using :data:`os.supports_dir_fd`. If it's unavailable,
1963 using it will raise a :exc:`NotImplementedError`.
1964
1965 .. _follow_symlinks:
1966
1967 * **not following symlinks:** If *follow_symlinks* is
1968 ``False``, and the last element of the path to operate on is a symbolic link,
1969 the function will operate on the symbolic link itself rather than the file
1970 pointed to by the link. For POSIX systems, Python will call the ``l...``
1971 variant of the function.
1972
1973 You can check whether or not *follow_symlinks* is supported for a particular
1974 function on your platform using :data:`os.supports_follow_symlinks`.
1975 If it's unavailable, using it will raise a :exc:`NotImplementedError`.
1976
1977
1978
1979 .. function:: access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)
1980
1981 Use the real uid/gid to test for access to *path*. Note that most operations
1982 will use the effective uid/gid, therefore this routine can be used in a
1983 suid/sgid environment to test if the invoking user has the specified access to
1984 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
1985 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
1986 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
1987 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
1988 information.
1989
1990 This function can support specifying :ref:`paths relative to directory
1991 descriptors <dir_fd>` and :ref:`not following symlinks <follow_symlinks>`.
1992
1993 If *effective_ids* is ``True``, :func:`access` will perform its access
1994 checks using the effective uid/gid instead of the real uid/gid.
1995 *effective_ids* may not be supported on your platform; you can check whether
1996 or not it is available using :data:`os.supports_effective_ids`. If it is
1997 unavailable, using it will raise a :exc:`NotImplementedError`.
1998
1999 .. note::
2000
2001 Using :func:`access` to check if a user is authorized to e.g. open a file
2002 before actually doing so using :func:`open` creates a security hole,
2003 because the user might exploit the short time interval between checking
2004 and opening the file to manipulate it. It's preferable to use :term:`EAFP`
2005 techniques. For example::
2006
2007 if os.access("myfile", os.R_OK):
2008 with open("myfile") as fp:
2009 return fp.read()
2010 return "some default data"
2011
2012 is better written as::
2013
2014 try:
2015 fp = open("myfile")
2016 except PermissionError:
2017 return "some default data"
2018 else:
2019 with fp:
2020 return fp.read()
2021
2022 .. note::
2023
2024 I/O operations may fail even when :func:`access` indicates that they would
2025 succeed, particularly for operations on network filesystems which may have
2026 permissions semantics beyond the usual POSIX permission-bit model.
2027
2028 .. versionchanged:: 3.3
2029 Added the *dir_fd*, *effective_ids*, and *follow_symlinks* parameters.
2030
2031 .. versionchanged:: 3.6
2032 Accepts a :term:`path-like object`.
2033
2034
2035 .. data:: F_OK
2036 R_OK
2037 W_OK
2038 X_OK
2039
2040 Values to pass as the *mode* parameter of :func:`access` to test the
2041 existence, readability, writability and executability of *path*,
2042 respectively.
2043
2044
2045 .. function:: chdir(path)
2046
2047 .. index:: single: directory; changing
2048
2049 Change the current working directory to *path*.
2050
2051 This function can support :ref:`specifying a file descriptor <path_fd>`. The
2052 descriptor must refer to an opened directory, not an open file.
2053
2054 This function can raise :exc:`OSError` and subclasses such as
2055 :exc:`FileNotFoundError`, :exc:`PermissionError`, and :exc:`NotADirectoryError`.
2056
2057 .. audit-event:: os.chdir path os.chdir
2058
2059 .. versionchanged:: 3.3
2060 Added support for specifying *path* as a file descriptor
2061 on some platforms.
2062
2063 .. versionchanged:: 3.6
2064 Accepts a :term:`path-like object`.
2065
2066
2067 .. function:: chflags(path, flags, *, follow_symlinks=True)
2068
2069 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
2070 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
2071
2072 * :const:`stat.UF_NODUMP`
2073 * :const:`stat.UF_IMMUTABLE`
2074 * :const:`stat.UF_APPEND`
2075 * :const:`stat.UF_OPAQUE`
2076 * :const:`stat.UF_NOUNLINK`
2077 * :const:`stat.UF_COMPRESSED`
2078 * :const:`stat.UF_HIDDEN`
2079 * :const:`stat.SF_ARCHIVED`
2080 * :const:`stat.SF_IMMUTABLE`
2081 * :const:`stat.SF_APPEND`
2082 * :const:`stat.SF_NOUNLINK`
2083 * :const:`stat.SF_SNAPSHOT`
2084
2085 This function can support :ref:`not following symlinks <follow_symlinks>`.
2086
2087 .. audit-event:: os.chflags path,flags os.chflags
2088
2089 .. availability:: Unix, not WASI.
2090
2091 .. versionchanged:: 3.3
2092 Added the *follow_symlinks* parameter.
2093
2094 .. versionchanged:: 3.6
2095 Accepts a :term:`path-like object`.
2096
2097
2098 .. function:: chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
2099
2100 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
2101 following values (as defined in the :mod:`stat` module) or bitwise ORed
2102 combinations of them:
2103
2104 * :const:`stat.S_ISUID`
2105 * :const:`stat.S_ISGID`
2106 * :const:`stat.S_ENFMT`
2107 * :const:`stat.S_ISVTX`
2108 * :const:`stat.S_IREAD`
2109 * :const:`stat.S_IWRITE`
2110 * :const:`stat.S_IEXEC`
2111 * :const:`stat.S_IRWXU`
2112 * :const:`stat.S_IRUSR`
2113 * :const:`stat.S_IWUSR`
2114 * :const:`stat.S_IXUSR`
2115 * :const:`stat.S_IRWXG`
2116 * :const:`stat.S_IRGRP`
2117 * :const:`stat.S_IWGRP`
2118 * :const:`stat.S_IXGRP`
2119 * :const:`stat.S_IRWXO`
2120 * :const:`stat.S_IROTH`
2121 * :const:`stat.S_IWOTH`
2122 * :const:`stat.S_IXOTH`
2123
2124 This function can support :ref:`specifying a file descriptor <path_fd>`,
2125 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
2126 following symlinks <follow_symlinks>`.
2127
2128 .. note::
2129
2130 Although Windows supports :func:`chmod`, you can only set the file's
2131 read-only flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
2132 constants or a corresponding integer value). All other bits are ignored.
2133 The default value of *follow_symlinks* is ``False`` on Windows.
2134
2135 The function is limited on WASI, see :ref:`wasm-availability` for more
2136 information.
2137
2138 .. audit-event:: os.chmod path,mode,dir_fd os.chmod
2139
2140 .. versionchanged:: 3.3
2141 Added support for specifying *path* as an open file descriptor,
2142 and the *dir_fd* and *follow_symlinks* arguments.
2143
2144 .. versionchanged:: 3.6
2145 Accepts a :term:`path-like object`.
2146
2147 .. versionchanged:: 3.13
2148 Added support for a file descriptor and the *follow_symlinks* argument
2149 on Windows.
2150
2151
2152 .. function:: chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)
2153
2154 Change the owner and group id of *path* to the numeric *uid* and *gid*. To
2155 leave one of the ids unchanged, set it to -1.
2156
2157 This function can support :ref:`specifying a file descriptor <path_fd>`,
2158 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
2159 following symlinks <follow_symlinks>`.
2160
2161 See :func:`shutil.chown` for a higher-level function that accepts names in
2162 addition to numeric ids.
2163
2164 .. audit-event:: os.chown path,uid,gid,dir_fd os.chown
2165
2166 .. availability:: Unix.
2167
2168 The function is limited on WASI, see :ref:`wasm-availability` for more
2169 information.
2170
2171 .. versionchanged:: 3.3
2172 Added support for specifying *path* as an open file descriptor,
2173 and the *dir_fd* and *follow_symlinks* arguments.
2174
2175 .. versionchanged:: 3.6
2176 Supports a :term:`path-like object`.
2177
2178
2179 .. function:: chroot(path)
2180
2181 Change the root directory of the current process to *path*.
2182
2183 .. availability:: Unix, not WASI, not Android.
2184
2185 .. versionchanged:: 3.6
2186 Accepts a :term:`path-like object`.
2187
2188
2189 .. function:: fchdir(fd)
2190
2191 Change the current working directory to the directory represented by the file
2192 descriptor *fd*. The descriptor must refer to an opened directory, not an
2193 open file. As of Python 3.3, this is equivalent to ``os.chdir(fd)``.
2194
2195 .. audit-event:: os.chdir path os.fchdir
2196
2197 .. availability:: Unix.
2198
2199
2200 .. function:: getcwd()
2201
2202 Return a string representing the current working directory.
2203
2204
2205 .. function:: getcwdb()
2206
2207 Return a bytestring representing the current working directory.
2208
2209 .. versionchanged:: 3.8
2210 The function now uses the UTF-8 encoding on Windows, rather than the ANSI
2211 code page: see :pep:`529` for the rationale. The function is no longer
2212 deprecated on Windows.
2213
2214
2215 .. function:: lchflags(path, flags)
2216
2217 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do
2218 not follow symbolic links. As of Python 3.3, this is equivalent to
2219 ``os.chflags(path, flags, follow_symlinks=False)``.
2220
2221 .. audit-event:: os.chflags path,flags os.lchflags
2222
2223 .. availability:: Unix, not WASI.
2224
2225 .. versionchanged:: 3.6
2226 Accepts a :term:`path-like object`.
2227
2228
2229 .. function:: lchmod(path, mode)
2230
2231 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
2232 affects the symlink rather than the target. See the docs for :func:`chmod`
2233 for possible values of *mode*. As of Python 3.3, this is equivalent to
2234 ``os.chmod(path, mode, follow_symlinks=False)``.
2235
2236 ``lchmod()`` is not part of POSIX, but Unix implementations may have it if
2237 changing the mode of symbolic links is supported.
2238
2239 .. audit-event:: os.chmod path,mode,dir_fd os.lchmod
2240
2241 .. availability:: Unix, Windows, not Linux, FreeBSD >= 1.3, NetBSD >= 1.3, not OpenBSD
2242
2243 .. versionchanged:: 3.6
2244 Accepts a :term:`path-like object`.
2245
2246 .. versionchanged:: 3.13
2247 Added support on Windows.
2248
2249 .. function:: lchown(path, uid, gid)
2250
2251 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
2252 function will not follow symbolic links. As of Python 3.3, this is equivalent
2253 to ``os.chown(path, uid, gid, follow_symlinks=False)``.
2254
2255 .. audit-event:: os.chown path,uid,gid,dir_fd os.lchown
2256
2257 .. availability:: Unix.
2258
2259 .. versionchanged:: 3.6
2260 Accepts a :term:`path-like object`.
2261
2262
2263 .. function:: link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)
2264
2265 Create a hard link pointing to *src* named *dst*.
2266
2267 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
2268 supply :ref:`paths relative to directory descriptors <dir_fd>`, and :ref:`not
2269 following symlinks <follow_symlinks>`.
2270
2271 .. audit-event:: os.link src,dst,src_dir_fd,dst_dir_fd os.link
2272
2273 .. availability:: Unix, Windows.
2274
2275 .. versionchanged:: 3.2
2276 Added Windows support.
2277
2278 .. versionchanged:: 3.3
2279 Added the *src_dir_fd*, *dst_dir_fd*, and *follow_symlinks* parameters.
2280
2281 .. versionchanged:: 3.6
2282 Accepts a :term:`path-like object` for *src* and *dst*.
2283
2284
2285 .. function:: listdir(path='.')
2286
2287 Return a list containing the names of the entries in the directory given by
2288 *path*. The list is in arbitrary order, and does not include the special
2289 entries ``'.'`` and ``'..'`` even if they are present in the directory.
2290 If a file is removed from or added to the directory during the call of
2291 this function, whether a name for that file be included is unspecified.
2292
2293 *path* may be a :term:`path-like object`. If *path* is of type ``bytes``
2294 (directly or indirectly through the :class:`PathLike` interface),
2295 the filenames returned will also be of type ``bytes``;
2296 in all other circumstances, they will be of type ``str``.
2297
2298 This function can also support :ref:`specifying a file descriptor
2299 <path_fd>`; the file descriptor must refer to a directory.
2300
2301 .. audit-event:: os.listdir path os.listdir
2302
2303 .. note::
2304 To encode ``str`` filenames to ``bytes``, use :func:`~os.fsencode`.
2305
2306 .. seealso::
2307
2308 The :func:`scandir` function returns directory entries along with
2309 file attribute information, giving better performance for many
2310 common use cases.
2311
2312 .. versionchanged:: 3.2
2313 The *path* parameter became optional.
2314
2315 .. versionchanged:: 3.3
2316 Added support for specifying *path* as an open file descriptor.
2317
2318 .. versionchanged:: 3.6
2319 Accepts a :term:`path-like object`.
2320
2321
2322 .. function:: listdrives()
2323
2324 Return a list containing the names of drives on a Windows system.
2325
2326 A drive name typically looks like ``'C:\\'``. Not every drive name
2327 will be associated with a volume, and some may be inaccessible for
2328 a variety of reasons, including permissions, network connectivity
2329 or missing media. This function does not test for access.
2330
2331 May raise :exc:`OSError` if an error occurs collecting the drive
2332 names.
2333
2334 .. audit-event:: os.listdrives "" os.listdrives
2335
2336 .. availability:: Windows
2337
2338 .. versionadded:: 3.12
2339
2340
2341 .. function:: listmounts(volume)
2342
2343 Return a list containing the mount points for a volume on a Windows
2344 system.
2345
2346 *volume* must be represented as a GUID path, like those returned by
2347 :func:`os.listvolumes`. Volumes may be mounted in multiple locations
2348 or not at all. In the latter case, the list will be empty. Mount
2349 points that are not associated with a volume will not be returned by
2350 this function.
2351
2352 The mount points return by this function will be absolute paths, and
2353 may be longer than the drive name.
2354
2355 Raises :exc:`OSError` if the volume is not recognized or if an error
2356 occurs collecting the paths.
2357
2358 .. audit-event:: os.listmounts volume os.listmounts
2359
2360 .. availability:: Windows
2361
2362 .. versionadded:: 3.12
2363
2364
2365 .. function:: listvolumes()
2366
2367 Return a list containing the volumes in the system.
2368
2369 Volumes are typically represented as a GUID path that looks like
2370 ``\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\``. Files can
2371 usually be accessed through a GUID path, permissions allowing.
2372 However, users are generally not familiar with them, and so the
2373 recommended use of this function is to retrieve mount points
2374 using :func:`os.listmounts`.
2375
2376 May raise :exc:`OSError` if an error occurs collecting the volumes.
2377
2378 .. audit-event:: os.listvolumes "" os.listvolumes
2379
2380 .. availability:: Windows
2381
2382 .. versionadded:: 3.12
2383
2384
2385 .. function:: lstat(path, *, dir_fd=None)
2386
2387 Perform the equivalent of an :c:func:`!lstat` system call on the given path.
2388 Similar to :func:`~os.stat`, but does not follow symbolic links. Return a
2389 :class:`stat_result` object.
2390
2391 On platforms that do not support symbolic links, this is an alias for
2392 :func:`~os.stat`.
2393
2394 As of Python 3.3, this is equivalent to ``os.stat(path, dir_fd=dir_fd,
2395 follow_symlinks=False)``.
2396
2397 This function can also support :ref:`paths relative to directory descriptors
2398 <dir_fd>`.
2399
2400 .. seealso::
2401
2402 The :func:`.stat` function.
2403
2404 .. versionchanged:: 3.2
2405 Added support for Windows 6.0 (Vista) symbolic links.
2406
2407 .. versionchanged:: 3.3
2408 Added the *dir_fd* parameter.
2409
2410 .. versionchanged:: 3.6
2411 Accepts a :term:`path-like object`.
2412
2413 .. versionchanged:: 3.8
2414 On Windows, now opens reparse points that represent another path
2415 (name surrogates), including symbolic links and directory junctions.
2416 Other kinds of reparse points are resolved by the operating system as
2417 for :func:`~os.stat`.
2418
2419
2420 .. function:: mkdir(path, mode=0o777, *, dir_fd=None)
2421
2422 Create a directory named *path* with numeric mode *mode*.
2423
2424 If the directory already exists, :exc:`FileExistsError` is raised. If a parent
2425 directory in the path does not exist, :exc:`FileNotFoundError` is raised.
2426
2427 .. _mkdir_modebits:
2428
2429 On some systems, *mode* is ignored. Where it is used, the current umask
2430 value is first masked out. If bits other than the last 9 (i.e. the last 3
2431 digits of the octal representation of the *mode*) are set, their meaning is
2432 platform-dependent. On some platforms, they are ignored and you should call
2433 :func:`chmod` explicitly to set them.
2434
2435 On Windows, a *mode* of ``0o700`` is specifically handled to apply access
2436 control to the new directory such that only the current user and
2437 administrators have access. Other values of *mode* are ignored.
2438
2439 This function can also support :ref:`paths relative to directory descriptors
2440 <dir_fd>`.
2441
2442 It is also possible to create temporary directories; see the
2443 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
2444
2445 .. audit-event:: os.mkdir path,mode,dir_fd os.mkdir
2446
2447 .. versionchanged:: 3.3
2448 Added the *dir_fd* parameter.
2449
2450 .. versionchanged:: 3.6
2451 Accepts a :term:`path-like object`.
2452
2453 .. versionchanged:: 3.13
2454 Windows now handles a *mode* of ``0o700``.
2455
2456
2457 .. function:: makedirs(name, mode=0o777, exist_ok=False)
2458
2459 .. index::
2460 single: directory; creating
2461 single: UNC paths; and os.makedirs()
2462
2463 Recursive directory creation function. Like :func:`mkdir`, but makes all
2464 intermediate-level directories needed to contain the leaf directory.
2465
2466 The *mode* parameter is passed to :func:`mkdir` for creating the leaf
2467 directory; see :ref:`the mkdir() description <mkdir_modebits>` for how it
2468 is interpreted. To set the file permission bits of any newly created parent
2469 directories you can set the umask before invoking :func:`makedirs`. The
2470 file permission bits of existing parent directories are not changed.
2471
2472 If *exist_ok* is ``False`` (the default), a :exc:`FileExistsError` is
2473 raised if the target directory already exists.
2474
2475 .. note::
2476
2477 :func:`makedirs` will become confused if the path elements to create
2478 include :data:`pardir` (eg. ".." on UNIX systems).
2479
2480 This function handles UNC paths correctly.
2481
2482 .. audit-event:: os.mkdir path,mode,dir_fd os.makedirs
2483
2484 .. versionchanged:: 3.2
2485 Added the *exist_ok* parameter.
2486
2487 .. versionchanged:: 3.4.1
2488
2489 Before Python 3.4.1, if *exist_ok* was ``True`` and the directory existed,
2490 :func:`makedirs` would still raise an error if *mode* did not match the
2491 mode of the existing directory. Since this behavior was impossible to
2492 implement safely, it was removed in Python 3.4.1. See :issue:`21082`.
2493
2494 .. versionchanged:: 3.6
2495 Accepts a :term:`path-like object`.
2496
2497 .. versionchanged:: 3.7
2498 The *mode* argument no longer affects the file permission bits of
2499 newly created intermediate-level directories.
2500
2501
2502 .. function:: mkfifo(path, mode=0o666, *, dir_fd=None)
2503
2504 Create a FIFO (a named pipe) named *path* with numeric mode *mode*.
2505 The current umask value is first masked out from the mode.
2506
2507 This function can also support :ref:`paths relative to directory descriptors
2508 <dir_fd>`.
2509
2510 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
2511 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
2512 rendezvous between "client" and "server" type processes: the server opens the
2513 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
2514 doesn't open the FIFO --- it just creates the rendezvous point.
2515
2516 .. availability:: Unix, not WASI.
2517
2518 .. versionchanged:: 3.3
2519 Added the *dir_fd* parameter.
2520
2521 .. versionchanged:: 3.6
2522 Accepts a :term:`path-like object`.
2523
2524
2525 .. function:: mknod(path, mode=0o600, device=0, *, dir_fd=None)
2526
2527 Create a filesystem node (file, device special file or named pipe) named
2528 *path*. *mode* specifies both the permissions to use and the type of node
2529 to be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
2530 ``stat.S_IFCHR``, ``stat.S_IFBLK``, and ``stat.S_IFIFO`` (those constants are
2531 available in :mod:`stat`). For ``stat.S_IFCHR`` and ``stat.S_IFBLK``,
2532 *device* defines the newly created device special file (probably using
2533 :func:`os.makedev`), otherwise it is ignored.
2534
2535 This function can also support :ref:`paths relative to directory descriptors
2536 <dir_fd>`.
2537
2538 .. availability:: Unix, not WASI.
2539
2540 .. versionchanged:: 3.3
2541 Added the *dir_fd* parameter.
2542
2543 .. versionchanged:: 3.6
2544 Accepts a :term:`path-like object`.
2545
2546
2547 .. function:: major(device, /)
2548
2549 Extract the device major number from a raw device number (usually the
2550 :attr:`st_dev` or :attr:`st_rdev` field from :c:struct:`stat`).
2551
2552
2553 .. function:: minor(device, /)
2554
2555 Extract the device minor number from a raw device number (usually the
2556 :attr:`st_dev` or :attr:`st_rdev` field from :c:struct:`stat`).
2557
2558
2559 .. function:: makedev(major, minor, /)
2560
2561 Compose a raw device number from the major and minor device numbers.
2562
2563
2564 .. function:: pathconf(path, name)
2565
2566 Return system configuration information relevant to a named file. *name*
2567 specifies the configuration value to retrieve; it may be a string which is the
2568 name of a defined system value; these names are specified in a number of
2569 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
2570 additional names as well. The names known to the host operating system are
2571 given in the ``pathconf_names`` dictionary. For configuration variables not
2572 included in that mapping, passing an integer for *name* is also accepted.
2573
2574 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2575 specific value for *name* is not supported by the host system, even if it is
2576 included in ``pathconf_names``, an :exc:`OSError` is raised with
2577 :const:`errno.EINVAL` for the error number.
2578
2579 This function can support :ref:`specifying a file descriptor
2580 <path_fd>`.
2581
2582 .. availability:: Unix.
2583
2584 .. versionchanged:: 3.6
2585 Accepts a :term:`path-like object`.
2586
2587
2588 .. data:: pathconf_names
2589
2590 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
2591 the integer values defined for those names by the host operating system. This
2592 can be used to determine the set of names known to the system.
2593
2594 .. availability:: Unix.
2595
2596
2597 .. function:: readlink(path, *, dir_fd=None)
2598
2599 Return a string representing the path to which the symbolic link points. The
2600 result may be either an absolute or relative pathname; if it is relative, it
2601 may be converted to an absolute pathname using
2602 ``os.path.join(os.path.dirname(path), result)``.
2603
2604 If the *path* is a string object (directly or indirectly through a
2605 :class:`PathLike` interface), the result will also be a string object,
2606 and the call may raise a UnicodeDecodeError. If the *path* is a bytes
2607 object (direct or indirectly), the result will be a bytes object.
2608
2609 This function can also support :ref:`paths relative to directory descriptors
2610 <dir_fd>`.
2611
2612 When trying to resolve a path that may contain links, use
2613 :func:`~os.path.realpath` to properly handle recursion and platform
2614 differences.
2615
2616 .. availability:: Unix, Windows.
2617
2618 .. versionchanged:: 3.2
2619 Added support for Windows 6.0 (Vista) symbolic links.
2620
2621 .. versionchanged:: 3.3
2622 Added the *dir_fd* parameter.
2623
2624 .. versionchanged:: 3.6
2625 Accepts a :term:`path-like object` on Unix.
2626
2627 .. versionchanged:: 3.8
2628 Accepts a :term:`path-like object` and a bytes object on Windows.
2629
2630 Added support for directory junctions, and changed to return the
2631 substitution path (which typically includes ``\\?\`` prefix) rather
2632 than the optional "print name" field that was previously returned.
2633
2634 .. function:: remove(path, *, dir_fd=None)
2635
2636 Remove (delete) the file *path*. If *path* is a directory, an
2637 :exc:`OSError` is raised. Use :func:`rmdir` to remove directories.
2638 If the file does not exist, a :exc:`FileNotFoundError` is raised.
2639
2640 This function can support :ref:`paths relative to directory descriptors
2641 <dir_fd>`.
2642
2643 On Windows, attempting to remove a file that is in use causes an exception to
2644 be raised; on Unix, the directory entry is removed but the storage allocated
2645 to the file is not made available until the original file is no longer in use.
2646
2647 This function is semantically identical to :func:`unlink`.
2648
2649 .. audit-event:: os.remove path,dir_fd os.remove
2650
2651 .. versionchanged:: 3.3
2652 Added the *dir_fd* parameter.
2653
2654 .. versionchanged:: 3.6
2655 Accepts a :term:`path-like object`.
2656
2657
2658 .. function:: removedirs(name)
2659
2660 .. index:: single: directory; deleting
2661
2662 Remove directories recursively. Works like :func:`rmdir` except that, if the
2663 leaf directory is successfully removed, :func:`removedirs` tries to
2664 successively remove every parent directory mentioned in *path* until an error
2665 is raised (which is ignored, because it generally means that a parent directory
2666 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
2667 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
2668 they are empty. Raises :exc:`OSError` if the leaf directory could not be
2669 successfully removed.
2670
2671 .. audit-event:: os.remove path,dir_fd os.removedirs
2672
2673 .. versionchanged:: 3.6
2674 Accepts a :term:`path-like object`.
2675
2676
2677 .. function:: rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
2678
2679 Rename the file or directory *src* to *dst*. If *dst* exists, the operation
2680 will fail with an :exc:`OSError` subclass in a number of cases:
2681
2682 On Windows, if *dst* exists a :exc:`FileExistsError` is always raised.
2683 The operation may fail if *src* and *dst* are on different filesystems. Use
2684 :func:`shutil.move` to support moves to a different filesystem.
2685
2686 On Unix, if *src* is a file and *dst* is a directory or vice-versa, an
2687 :exc:`IsADirectoryError` or a :exc:`NotADirectoryError` will be raised
2688 respectively. If both are directories and *dst* is empty, *dst* will be
2689 silently replaced. If *dst* is a non-empty directory, an :exc:`OSError`
2690 is raised. If both are files, *dst* will be replaced silently if the user
2691 has permission. The operation may fail on some Unix flavors if *src* and
2692 *dst* are on different filesystems. If successful, the renaming will be an
2693 atomic operation (this is a POSIX requirement).
2694
2695 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
2696 supply :ref:`paths relative to directory descriptors <dir_fd>`.
2697
2698 If you want cross-platform overwriting of the destination, use :func:`replace`.
2699
2700 .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.rename
2701
2702 .. versionchanged:: 3.3
2703 Added the *src_dir_fd* and *dst_dir_fd* parameters.
2704
2705 .. versionchanged:: 3.6
2706 Accepts a :term:`path-like object` for *src* and *dst*.
2707
2708
2709 .. function:: renames(old, new)
2710
2711 Recursive directory or file renaming function. Works like :func:`rename`, except
2712 creation of any intermediate directories needed to make the new pathname good is
2713 attempted first. After the rename, directories corresponding to rightmost path
2714 segments of the old name will be pruned away using :func:`removedirs`.
2715
2716 .. note::
2717
2718 This function can fail with the new directory structure made if you lack
2719 permissions needed to remove the leaf directory or file.
2720
2721 .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.renames
2722
2723 .. versionchanged:: 3.6
2724 Accepts a :term:`path-like object` for *old* and *new*.
2725
2726
2727 .. function:: replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
2728
2729 Rename the file or directory *src* to *dst*. If *dst* is a non-empty directory,
2730 :exc:`OSError` will be raised. If *dst* exists and is a file, it will
2731 be replaced silently if the user has permission. The operation may fail
2732 if *src* and *dst* are on different filesystems. If successful,
2733 the renaming will be an atomic operation (this is a POSIX requirement).
2734
2735 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
2736 supply :ref:`paths relative to directory descriptors <dir_fd>`.
2737
2738 .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.replace
2739
2740 .. versionadded:: 3.3
2741
2742 .. versionchanged:: 3.6
2743 Accepts a :term:`path-like object` for *src* and *dst*.
2744
2745
2746 .. function:: rmdir(path, *, dir_fd=None)
2747
2748 Remove (delete) the directory *path*. If the directory does not exist or is
2749 not empty, a :exc:`FileNotFoundError` or an :exc:`OSError` is raised
2750 respectively. In order to remove whole directory trees,
2751 :func:`shutil.rmtree` can be used.
2752
2753 This function can support :ref:`paths relative to directory descriptors
2754 <dir_fd>`.
2755
2756 .. audit-event:: os.rmdir path,dir_fd os.rmdir
2757
2758 .. versionchanged:: 3.3
2759 Added the *dir_fd* parameter.
2760
2761 .. versionchanged:: 3.6
2762 Accepts a :term:`path-like object`.
2763
2764
2765 .. function:: scandir(path='.')
2766
2767 Return an iterator of :class:`os.DirEntry` objects corresponding to the
2768 entries in the directory given by *path*. The entries are yielded in
2769 arbitrary order, and the special entries ``'.'`` and ``'..'`` are not
2770 included. If a file is removed from or added to the directory after
2771 creating the iterator, whether an entry for that file be included is
2772 unspecified.
2773
2774 Using :func:`scandir` instead of :func:`listdir` can significantly
2775 increase the performance of code that also needs file type or file
2776 attribute information, because :class:`os.DirEntry` objects expose this
2777 information if the operating system provides it when scanning a directory.
2778 All :class:`os.DirEntry` methods may perform a system call, but
2779 :func:`~os.DirEntry.is_dir` and :func:`~os.DirEntry.is_file` usually only
2780 require a system call for symbolic links; :func:`os.DirEntry.stat`
2781 always requires a system call on Unix but only requires one for
2782 symbolic links on Windows.
2783
2784 *path* may be a :term:`path-like object`. If *path* is of type ``bytes``
2785 (directly or indirectly through the :class:`PathLike` interface),
2786 the type of the :attr:`~os.DirEntry.name` and :attr:`~os.DirEntry.path`
2787 attributes of each :class:`os.DirEntry` will be ``bytes``; in all other
2788 circumstances, they will be of type ``str``.
2789
2790 This function can also support :ref:`specifying a file descriptor
2791 <path_fd>`; the file descriptor must refer to a directory.
2792
2793 .. audit-event:: os.scandir path os.scandir
2794
2795 The :func:`scandir` iterator supports the :term:`context manager` protocol
2796 and has the following method:
2797
2798 .. method:: scandir.close()
2799
2800 Close the iterator and free acquired resources.
2801
2802 This is called automatically when the iterator is exhausted or garbage
2803 collected, or when an error happens during iterating. However it
2804 is advisable to call it explicitly or use the :keyword:`with`
2805 statement.
2806
2807 .. versionadded:: 3.6
2808
2809 The following example shows a simple use of :func:`scandir` to display all
2810 the files (excluding directories) in the given *path* that don't start with
2811 ``'.'``. The ``entry.is_file()`` call will generally not make an additional
2812 system call::
2813
2814 with os.scandir(path) as it:
2815 for entry in it:
2816 if not entry.name.startswith('.') and entry.is_file():
2817 print(entry.name)
2818
2819 .. note::
2820
2821 On Unix-based systems, :func:`scandir` uses the system's
2822 `opendir() <https://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html>`_
2823 and
2824 `readdir() <https://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html>`_
2825 functions. On Windows, it uses the Win32
2826 `FindFirstFileW <https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx>`_
2827 and
2828 `FindNextFileW <https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx>`_
2829 functions.
2830
2831 .. versionadded:: 3.5
2832
2833 .. versionchanged:: 3.6
2834 Added support for the :term:`context manager` protocol and the
2835 :func:`~scandir.close` method. If a :func:`scandir` iterator is neither
2836 exhausted nor explicitly closed a :exc:`ResourceWarning` will be emitted
2837 in its destructor.
2838
2839 The function accepts a :term:`path-like object`.
2840
2841 .. versionchanged:: 3.7
2842 Added support for :ref:`file descriptors <path_fd>` on Unix.
2843
2844
2845 .. class:: DirEntry
2846
2847 Object yielded by :func:`scandir` to expose the file path and other file
2848 attributes of a directory entry.
2849
2850 :func:`scandir` will provide as much of this information as possible without
2851 making additional system calls. When a ``stat()`` or ``lstat()`` system call
2852 is made, the ``os.DirEntry`` object will cache the result.
2853
2854 ``os.DirEntry`` instances are not intended to be stored in long-lived data
2855 structures; if you know the file metadata has changed or if a long time has
2856 elapsed since calling :func:`scandir`, call ``os.stat(entry.path)`` to fetch
2857 up-to-date information.
2858
2859 Because the ``os.DirEntry`` methods can make operating system calls, they may
2860 also raise :exc:`OSError`. If you need very fine-grained
2861 control over errors, you can catch :exc:`OSError` when calling one of the
2862 ``os.DirEntry`` methods and handle as appropriate.
2863
2864 To be directly usable as a :term:`path-like object`, ``os.DirEntry``
2865 implements the :class:`PathLike` interface.
2866
2867 Attributes and methods on a ``os.DirEntry`` instance are as follows:
2868
2869 .. attribute:: name
2870
2871 The entry's base filename, relative to the :func:`scandir` *path*
2872 argument.
2873
2874 The :attr:`name` attribute will be ``bytes`` if the :func:`scandir`
2875 *path* argument is of type ``bytes`` and ``str`` otherwise. Use
2876 :func:`~os.fsdecode` to decode byte filenames.
2877
2878 .. attribute:: path
2879
2880 The entry's full path name: equivalent to ``os.path.join(scandir_path,
2881 entry.name)`` where *scandir_path* is the :func:`scandir` *path*
2882 argument. The path is only absolute if the :func:`scandir` *path*
2883 argument was absolute. If the :func:`scandir` *path*
2884 argument was a :ref:`file descriptor <path_fd>`, the :attr:`path`
2885 attribute is the same as the :attr:`name` attribute.
2886
2887 The :attr:`path` attribute will be ``bytes`` if the :func:`scandir`
2888 *path* argument is of type ``bytes`` and ``str`` otherwise. Use
2889 :func:`~os.fsdecode` to decode byte filenames.
2890
2891 .. method:: inode()
2892
2893 Return the inode number of the entry.
2894
2895 The result is cached on the ``os.DirEntry`` object. Use
2896 ``os.stat(entry.path, follow_symlinks=False).st_ino`` to fetch up-to-date
2897 information.
2898
2899 On the first, uncached call, a system call is required on Windows but
2900 not on Unix.
2901
2902 .. method:: is_dir(*, follow_symlinks=True)
2903
2904 Return ``True`` if this entry is a directory or a symbolic link pointing
2905 to a directory; return ``False`` if the entry is or points to any other
2906 kind of file, or if it doesn't exist anymore.
2907
2908 If *follow_symlinks* is ``False``, return ``True`` only if this entry
2909 is a directory (without following symlinks); return ``False`` if the
2910 entry is any other kind of file or if it doesn't exist anymore.
2911
2912 The result is cached on the ``os.DirEntry`` object, with a separate cache
2913 for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` along
2914 with :func:`stat.S_ISDIR` to fetch up-to-date information.
2915
2916 On the first, uncached call, no system call is required in most cases.
2917 Specifically, for non-symlinks, neither Windows or Unix require a system
2918 call, except on certain Unix file systems, such as network file systems,
2919 that return ``dirent.d_type == DT_UNKNOWN``. If the entry is a symlink,
2920 a system call will be required to follow the symlink unless
2921 *follow_symlinks* is ``False``.
2922
2923 This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2924 but :exc:`FileNotFoundError` is caught and not raised.
2925
2926 .. method:: is_file(*, follow_symlinks=True)
2927
2928 Return ``True`` if this entry is a file or a symbolic link pointing to a
2929 file; return ``False`` if the entry is or points to a directory or other
2930 non-file entry, or if it doesn't exist anymore.
2931
2932 If *follow_symlinks* is ``False``, return ``True`` only if this entry
2933 is a file (without following symlinks); return ``False`` if the entry is
2934 a directory or other non-file entry, or if it doesn't exist anymore.
2935
2936 The result is cached on the ``os.DirEntry`` object. Caching, system calls
2937 made, and exceptions raised are as per :func:`~os.DirEntry.is_dir`.
2938
2939 .. method:: is_symlink()
2940
2941 Return ``True`` if this entry is a symbolic link (even if broken);
2942 return ``False`` if the entry points to a directory or any kind of file,
2943 or if it doesn't exist anymore.
2944
2945 The result is cached on the ``os.DirEntry`` object. Call
2946 :func:`os.path.islink` to fetch up-to-date information.
2947
2948 On the first, uncached call, no system call is required in most cases.
2949 Specifically, neither Windows or Unix require a system call, except on
2950 certain Unix file systems, such as network file systems, that return
2951 ``dirent.d_type == DT_UNKNOWN``.
2952
2953 This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2954 but :exc:`FileNotFoundError` is caught and not raised.
2955
2956 .. method:: is_junction()
2957
2958 Return ``True`` if this entry is a junction (even if broken);
2959 return ``False`` if the entry points to a regular directory, any kind
2960 of file, a symlink, or if it doesn't exist anymore.
2961
2962 The result is cached on the ``os.DirEntry`` object. Call
2963 :func:`os.path.isjunction` to fetch up-to-date information.
2964
2965 .. versionadded:: 3.12
2966
2967 .. method:: stat(*, follow_symlinks=True)
2968
2969 Return a :class:`stat_result` object for this entry. This method
2970 follows symbolic links by default; to stat a symbolic link add the
2971 ``follow_symlinks=False`` argument.
2972
2973 On Unix, this method always requires a system call. On Windows, it
2974 only requires a system call if *follow_symlinks* is ``True`` and the
2975 entry is a reparse point (for example, a symbolic link or directory
2976 junction).
2977
2978 On Windows, the ``st_ino``, ``st_dev`` and ``st_nlink`` attributes of the
2979 :class:`stat_result` are always set to zero. Call :func:`os.stat` to
2980 get these attributes.
2981
2982 The result is cached on the ``os.DirEntry`` object, with a separate cache
2983 for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` to
2984 fetch up-to-date information.
2985
2986 Note that there is a nice correspondence between several attributes
2987 and methods of ``os.DirEntry`` and of :class:`pathlib.Path`. In
2988 particular, the ``name`` attribute has the same
2989 meaning, as do the ``is_dir()``, ``is_file()``, ``is_symlink()``,
2990 ``is_junction()``, and ``stat()`` methods.
2991
2992 .. versionadded:: 3.5
2993
2994 .. versionchanged:: 3.6
2995 Added support for the :class:`~os.PathLike` interface. Added support
2996 for :class:`bytes` paths on Windows.
2997
2998 .. versionchanged:: 3.12
2999 The ``st_ctime`` attribute of a stat result is deprecated on Windows.
3000 The file creation time is properly available as ``st_birthtime``, and
3001 in the future ``st_ctime`` may be changed to return zero or the
3002 metadata change time, if available.
3003
3004
3005 .. function:: stat(path, *, dir_fd=None, follow_symlinks=True)
3006
3007 Get the status of a file or a file descriptor. Perform the equivalent of a
3008 :c:func:`stat` system call on the given path. *path* may be specified as
3009 either a string or bytes -- directly or indirectly through the :class:`PathLike`
3010 interface -- or as an open file descriptor. Return a :class:`stat_result`
3011 object.
3012
3013 This function normally follows symlinks; to stat a symlink add the argument
3014 ``follow_symlinks=False``, or use :func:`lstat`.
3015
3016 This function can support :ref:`specifying a file descriptor <path_fd>` and
3017 :ref:`not following symlinks <follow_symlinks>`.
3018
3019 On Windows, passing ``follow_symlinks=False`` will disable following all
3020 name-surrogate reparse points, which includes symlinks and directory
3021 junctions. Other types of reparse points that do not resemble links or that
3022 the operating system is unable to follow will be opened directly. When
3023 following a chain of multiple links, this may result in the original link
3024 being returned instead of the non-link that prevented full traversal. To
3025 obtain stat results for the final path in this case, use the
3026 :func:`os.path.realpath` function to resolve the path name as far as
3027 possible and call :func:`lstat` on the result. This does not apply to
3028 dangling symlinks or junction points, which will raise the usual exceptions.
3029
3030 .. index:: pair: module; stat
3031
3032 Example::
3033
3034 >>> import os
3035 >>> statinfo = os.stat('somefile.txt')
3036 >>> statinfo
3037 os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
3038 st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
3039 st_mtime=1297230027, st_ctime=1297230027)
3040 >>> statinfo.st_size
3041 264
3042
3043 .. seealso::
3044
3045 :func:`fstat` and :func:`lstat` functions.
3046
3047 .. versionchanged:: 3.3
3048 Added the *dir_fd* and *follow_symlinks* parameters,
3049 specifying a file descriptor instead of a path.
3050
3051 .. versionchanged:: 3.6
3052 Accepts a :term:`path-like object`.
3053
3054 .. versionchanged:: 3.8
3055 On Windows, all reparse points that can be resolved by the operating
3056 system are now followed, and passing ``follow_symlinks=False``
3057 disables following all name surrogate reparse points. If the operating
3058 system reaches a reparse point that it is not able to follow, *stat* now
3059 returns the information for the original path as if
3060 ``follow_symlinks=False`` had been specified instead of raising an error.
3061
3062
3063 .. class:: stat_result
3064
3065 Object whose attributes correspond roughly to the members of the
3066 :c:struct:`stat` structure. It is used for the result of :func:`os.stat`,
3067 :func:`os.fstat` and :func:`os.lstat`.
3068
3069 Attributes:
3070
3071 .. attribute:: st_mode
3072
3073 File mode: file type and file mode bits (permissions).
3074
3075 .. attribute:: st_ino
3076
3077 Platform dependent, but if non-zero, uniquely identifies the
3078 file for a given value of ``st_dev``. Typically:
3079
3080 * the inode number on Unix,
3081 * the `file index
3082 <https://msdn.microsoft.com/en-us/library/aa363788>`_ on
3083 Windows
3084
3085 .. attribute:: st_dev
3086
3087 Identifier of the device on which this file resides.
3088
3089 .. attribute:: st_nlink
3090
3091 Number of hard links.
3092
3093 .. attribute:: st_uid
3094
3095 User identifier of the file owner.
3096
3097 .. attribute:: st_gid
3098
3099 Group identifier of the file owner.
3100
3101 .. attribute:: st_size
3102
3103 Size of the file in bytes, if it is a regular file or a symbolic link.
3104 The size of a symbolic link is the length of the pathname it contains,
3105 without a terminating null byte.
3106
3107 Timestamps:
3108
3109 .. attribute:: st_atime
3110
3111 Time of most recent access expressed in seconds.
3112
3113 .. attribute:: st_mtime
3114
3115 Time of most recent content modification expressed in seconds.
3116
3117 .. attribute:: st_ctime
3118
3119 Time of most recent metadata change expressed in seconds.
3120
3121 .. versionchanged:: 3.12
3122 ``st_ctime`` is deprecated on Windows. Use ``st_birthtime`` for
3123 the file creation time. In the future, ``st_ctime`` will contain
3124 the time of the most recent metadata change, as for other platforms.
3125
3126 .. attribute:: st_atime_ns
3127
3128 Time of most recent access expressed in nanoseconds as an integer.
3129
3130 .. versionadded:: 3.3
3131
3132 .. attribute:: st_mtime_ns
3133
3134 Time of most recent content modification expressed in nanoseconds as an
3135 integer.
3136
3137 .. versionadded:: 3.3
3138
3139 .. attribute:: st_ctime_ns
3140
3141 Time of most recent metadata change expressed in nanoseconds as an
3142 integer.
3143
3144 .. versionadded:: 3.3
3145
3146 .. versionchanged:: 3.12
3147 ``st_ctime_ns`` is deprecated on Windows. Use ``st_birthtime_ns``
3148 for the file creation time. In the future, ``st_ctime`` will contain
3149 the time of the most recent metadata change, as for other platforms.
3150
3151 .. attribute:: st_birthtime
3152
3153 Time of file creation expressed in seconds. This attribute is not
3154 always available, and may raise :exc:`AttributeError`.
3155
3156 .. versionchanged:: 3.12
3157 ``st_birthtime`` is now available on Windows.
3158
3159 .. attribute:: st_birthtime_ns
3160
3161 Time of file creation expressed in nanoseconds as an integer.
3162 This attribute is not always available, and may raise
3163 :exc:`AttributeError`.
3164
3165 .. versionadded:: 3.12
3166
3167 .. note::
3168
3169 The exact meaning and resolution of the :attr:`st_atime`,
3170 :attr:`st_mtime`, :attr:`st_ctime` and :attr:`st_birthtime` attributes
3171 depend on the operating system and the file system. For example, on
3172 Windows systems using the FAT32 file systems, :attr:`st_mtime` has
3173 2-second resolution, and :attr:`st_atime` has only 1-day resolution.
3174 See your operating system documentation for details.
3175
3176 Similarly, although :attr:`st_atime_ns`, :attr:`st_mtime_ns`,
3177 :attr:`st_ctime_ns` and :attr:`st_birthtime_ns` are always expressed in
3178 nanoseconds, many systems do not provide nanosecond precision. On
3179 systems that do provide nanosecond precision, the floating-point object
3180 used to store :attr:`st_atime`, :attr:`st_mtime`, :attr:`st_ctime` and
3181 :attr:`st_birthtime` cannot preserve all of it, and as such will be
3182 slightly inexact. If you need the exact timestamps you should always use
3183 :attr:`st_atime_ns`, :attr:`st_mtime_ns`, :attr:`st_ctime_ns` and
3184 :attr:`st_birthtime_ns`.
3185
3186 On some Unix systems (such as Linux), the following attributes may also be
3187 available:
3188
3189 .. attribute:: st_blocks
3190
3191 Number of 512-byte blocks allocated for file.
3192 This may be smaller than :attr:`st_size`/512 when the file has holes.
3193
3194 .. attribute:: st_blksize
3195
3196 "Preferred" blocksize for efficient file system I/O. Writing to a file in
3197 smaller chunks may cause an inefficient read-modify-rewrite.
3198
3199 .. attribute:: st_rdev
3200
3201 Type of device if an inode device.
3202
3203 .. attribute:: st_flags
3204
3205 User defined flags for file.
3206
3207 On other Unix systems (such as FreeBSD), the following attributes may be
3208 available (but may be only filled out if root tries to use them):
3209
3210 .. attribute:: st_gen
3211
3212 File generation number.
3213
3214 On Solaris and derivatives, the following attributes may also be
3215 available:
3216
3217 .. attribute:: st_fstype
3218
3219 String that uniquely identifies the type of the filesystem that
3220 contains the file.
3221
3222 On macOS systems, the following attributes may also be available:
3223
3224 .. attribute:: st_rsize
3225
3226 Real size of the file.
3227
3228 .. attribute:: st_creator
3229
3230 Creator of the file.
3231
3232 .. attribute:: st_type
3233
3234 File type.
3235
3236 On Windows systems, the following attributes are also available:
3237
3238 .. attribute:: st_file_attributes
3239
3240 Windows file attributes: ``dwFileAttributes`` member of the
3241 ``BY_HANDLE_FILE_INFORMATION`` structure returned by
3242 :c:func:`!GetFileInformationByHandle`.
3243 See the :const:`!FILE_ATTRIBUTE_* <stat.FILE_ATTRIBUTE_ARCHIVE>`
3244 constants in the :mod:`stat` module.
3245
3246 .. versionadded:: 3.5
3247
3248 .. attribute:: st_reparse_tag
3249
3250 When :attr:`st_file_attributes` has the :const:`~stat.FILE_ATTRIBUTE_REPARSE_POINT`
3251 set, this field contains the tag identifying the type of reparse point.
3252 See the :const:`IO_REPARSE_TAG_* <stat.IO_REPARSE_TAG_SYMLINK>`
3253 constants in the :mod:`stat` module.
3254
3255 The standard module :mod:`stat` defines functions and constants that are
3256 useful for extracting information from a :c:struct:`stat` structure. (On
3257 Windows, some items are filled with dummy values.)
3258
3259 For backward compatibility, a :class:`stat_result` instance is also
3260 accessible as a tuple of at least 10 integers giving the most important (and
3261 portable) members of the :c:struct:`stat` structure, in the order
3262 :attr:`st_mode`, :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`,
3263 :attr:`st_uid`, :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`,
3264 :attr:`st_mtime`, :attr:`st_ctime`. More items may be added at the end by
3265 some implementations. For compatibility with older Python versions,
3266 accessing :class:`stat_result` as a tuple always returns integers.
3267
3268 .. versionchanged:: 3.5
3269 Windows now returns the file index as :attr:`st_ino` when
3270 available.
3271
3272 .. versionchanged:: 3.7
3273 Added the :attr:`st_fstype` member to Solaris/derivatives.
3274
3275 .. versionchanged:: 3.8
3276 Added the :attr:`st_reparse_tag` member on Windows.
3277
3278 .. versionchanged:: 3.8
3279 On Windows, the :attr:`st_mode` member now identifies special
3280 files as :const:`S_IFCHR`, :const:`S_IFIFO` or :const:`S_IFBLK`
3281 as appropriate.
3282
3283 .. versionchanged:: 3.12
3284 On Windows, :attr:`st_ctime` is deprecated. Eventually, it will
3285 contain the last metadata change time, for consistency with other
3286 platforms, but for now still contains creation time.
3287 Use :attr:`st_birthtime` for the creation time.
3288
3289 On Windows, :attr:`st_ino` may now be up to 128 bits, depending
3290 on the file system. Previously it would not be above 64 bits, and
3291 larger file identifiers would be arbitrarily packed.
3292
3293 On Windows, :attr:`st_rdev` no longer returns a value. Previously
3294 it would contain the same as :attr:`st_dev`, which was incorrect.
3295
3296 Added the :attr:`st_birthtime` member on Windows.
3297
3298
3299 .. function:: statvfs(path)
3300
3301 Perform a :c:func:`!statvfs` system call on the given path. The return value is
3302 an object whose attributes describe the filesystem on the given path, and
3303 correspond to the members of the :c:struct:`statvfs` structure, namely:
3304 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
3305 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
3306 :attr:`f_flag`, :attr:`f_namemax`, :attr:`f_fsid`.
3307
3308 Two module-level constants are defined for the :attr:`f_flag` attribute's
3309 bit-flags: if :const:`ST_RDONLY` is set, the filesystem is mounted
3310 read-only, and if :const:`ST_NOSUID` is set, the semantics of
3311 setuid/setgid bits are disabled or not supported.
3312
3313 Additional module-level constants are defined for GNU/glibc based systems.
3314 These are :const:`ST_NODEV` (disallow access to device special files),
3315 :const:`ST_NOEXEC` (disallow program execution), :const:`ST_SYNCHRONOUS`
3316 (writes are synced at once), :const:`ST_MANDLOCK` (allow mandatory locks on an FS),
3317 :const:`ST_WRITE` (write on file/directory/symlink), :const:`ST_APPEND`
3318 (append-only file), :const:`ST_IMMUTABLE` (immutable file), :const:`ST_NOATIME`
3319 (do not update access times), :const:`ST_NODIRATIME` (do not update directory access
3320 times), :const:`ST_RELATIME` (update atime relative to mtime/ctime).
3321
3322 This function can support :ref:`specifying a file descriptor <path_fd>`.
3323
3324 .. availability:: Unix.
3325
3326 .. versionchanged:: 3.2
3327 The :const:`ST_RDONLY` and :const:`ST_NOSUID` constants were added.
3328
3329 .. versionchanged:: 3.3
3330 Added support for specifying *path* as an open file descriptor.
3331
3332 .. versionchanged:: 3.4
3333 The :const:`ST_NODEV`, :const:`ST_NOEXEC`, :const:`ST_SYNCHRONOUS`,
3334 :const:`ST_MANDLOCK`, :const:`ST_WRITE`, :const:`ST_APPEND`,
3335 :const:`ST_IMMUTABLE`, :const:`ST_NOATIME`, :const:`ST_NODIRATIME`,
3336 and :const:`ST_RELATIME` constants were added.
3337
3338 .. versionchanged:: 3.6
3339 Accepts a :term:`path-like object`.
3340
3341 .. versionchanged:: 3.7
3342 Added the :attr:`f_fsid` attribute.
3343
3344
3345 .. data:: supports_dir_fd
3346
3347 A :class:`set` object indicating which functions in the :mod:`os`
3348 module accept an open file descriptor for their *dir_fd* parameter.
3349 Different platforms provide different features, and the underlying
3350 functionality Python uses to implement the *dir_fd* parameter is not
3351 available on all platforms Python supports. For consistency's sake,
3352 functions that may support *dir_fd* always allow specifying the
3353 parameter, but will throw an exception if the functionality is used
3354 when it's not locally available. (Specifying ``None`` for *dir_fd*
3355 is always supported on all platforms.)
3356
3357 To check whether a particular function accepts an open file descriptor
3358 for its *dir_fd* parameter, use the ``in`` operator on ``supports_dir_fd``.
3359 As an example, this expression evaluates to ``True`` if :func:`os.stat`
3360 accepts open file descriptors for *dir_fd* on the local platform::
3361
3362 os.stat in os.supports_dir_fd
3363
3364 Currently *dir_fd* parameters only work on Unix platforms;
3365 none of them work on Windows.
3366
3367 .. versionadded:: 3.3
3368
3369
3370 .. data:: supports_effective_ids
3371
3372 A :class:`set` object indicating whether :func:`os.access` permits
3373 specifying ``True`` for its *effective_ids* parameter on the local platform.
3374 (Specifying ``False`` for *effective_ids* is always supported on all
3375 platforms.) If the local platform supports it, the collection will contain
3376 :func:`os.access`; otherwise it will be empty.
3377
3378 This expression evaluates to ``True`` if :func:`os.access` supports
3379 ``effective_ids=True`` on the local platform::
3380
3381 os.access in os.supports_effective_ids
3382
3383 Currently *effective_ids* is only supported on Unix platforms;
3384 it does not work on Windows.
3385
3386 .. versionadded:: 3.3
3387
3388
3389 .. data:: supports_fd
3390
3391 A :class:`set` object indicating which functions in the
3392 :mod:`os` module permit specifying their *path* parameter as an open file
3393 descriptor on the local platform. Different platforms provide different
3394 features, and the underlying functionality Python uses to accept open file
3395 descriptors as *path* arguments is not available on all platforms Python
3396 supports.
3397
3398 To determine whether a particular function permits specifying an open file
3399 descriptor for its *path* parameter, use the ``in`` operator on
3400 ``supports_fd``. As an example, this expression evaluates to ``True`` if
3401 :func:`os.chdir` accepts open file descriptors for *path* on your local
3402 platform::
3403
3404 os.chdir in os.supports_fd
3405
3406 .. versionadded:: 3.3
3407
3408
3409 .. data:: supports_follow_symlinks
3410
3411 A :class:`set` object indicating which functions in the :mod:`os` module
3412 accept ``False`` for their *follow_symlinks* parameter on the local platform.
3413 Different platforms provide different features, and the underlying
3414 functionality Python uses to implement *follow_symlinks* is not available
3415 on all platforms Python supports. For consistency's sake, functions that
3416 may support *follow_symlinks* always allow specifying the parameter, but
3417 will throw an exception if the functionality is used when it's not locally
3418 available. (Specifying ``True`` for *follow_symlinks* is always supported
3419 on all platforms.)
3420
3421 To check whether a particular function accepts ``False`` for its
3422 *follow_symlinks* parameter, use the ``in`` operator on
3423 ``supports_follow_symlinks``. As an example, this expression evaluates
3424 to ``True`` if you may specify ``follow_symlinks=False`` when calling
3425 :func:`os.stat` on the local platform::
3426
3427 os.stat in os.supports_follow_symlinks
3428
3429 .. versionadded:: 3.3
3430
3431
3432 .. function:: symlink(src, dst, target_is_directory=False, *, dir_fd=None)
3433
3434 Create a symbolic link pointing to *src* named *dst*.
3435
3436 The *src* parameter refers to the target of the link (the file or directory being linked to),
3437 and *dst* is the name of the link being created.
3438
3439 On Windows, a symlink represents either a file or a directory, and does not
3440 morph to the target dynamically. If the target is present, the type of the
3441 symlink will be created to match. Otherwise, the symlink will be created
3442 as a directory if *target_is_directory* is ``True`` or a file symlink (the
3443 default) otherwise. On non-Windows platforms, *target_is_directory* is ignored.
3444
3445 This function can support :ref:`paths relative to directory descriptors
3446 <dir_fd>`.
3447
3448 .. note::
3449
3450 On newer versions of Windows 10, unprivileged accounts can create symlinks
3451 if Developer Mode is enabled. When Developer Mode is not available/enabled,
3452 the *SeCreateSymbolicLinkPrivilege* privilege is required, or the process
3453 must be run as an administrator.
3454
3455
3456 :exc:`OSError` is raised when the function is called by an unprivileged
3457 user.
3458
3459 .. audit-event:: os.symlink src,dst,dir_fd os.symlink
3460
3461 .. availability:: Unix, Windows.
3462
3463 The function is limited on WASI, see :ref:`wasm-availability` for more
3464 information.
3465
3466 .. versionchanged:: 3.2
3467 Added support for Windows 6.0 (Vista) symbolic links.
3468
3469 .. versionchanged:: 3.3
3470 Added the *dir_fd* parameter, and now allow *target_is_directory*
3471 on non-Windows platforms.
3472
3473 .. versionchanged:: 3.6
3474 Accepts a :term:`path-like object` for *src* and *dst*.
3475
3476 .. versionchanged:: 3.8
3477 Added support for unelevated symlinks on Windows with Developer Mode.
3478
3479
3480 .. function:: sync()
3481
3482 Force write of everything to disk.
3483
3484 .. availability:: Unix.
3485
3486 .. versionadded:: 3.3
3487
3488
3489 .. function:: truncate(path, length)
3490
3491 Truncate the file corresponding to *path*, so that it is at most
3492 *length* bytes in size.
3493
3494 This function can support :ref:`specifying a file descriptor <path_fd>`.
3495
3496 .. audit-event:: os.truncate path,length os.truncate
3497
3498 .. availability:: Unix, Windows.
3499
3500 .. versionadded:: 3.3
3501
3502 .. versionchanged:: 3.5
3503 Added support for Windows
3504
3505 .. versionchanged:: 3.6
3506 Accepts a :term:`path-like object`.
3507
3508
3509 .. function:: unlink(path, *, dir_fd=None)
3510
3511 Remove (delete) the file *path*. This function is semantically
3512 identical to :func:`remove`; the ``unlink`` name is its
3513 traditional Unix name. Please see the documentation for
3514 :func:`remove` for further information.
3515
3516 .. audit-event:: os.remove path,dir_fd os.unlink
3517
3518 .. versionchanged:: 3.3
3519 Added the *dir_fd* parameter.
3520
3521 .. versionchanged:: 3.6
3522 Accepts a :term:`path-like object`.
3523
3524
3525 .. function:: utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)
3526
3527 Set the access and modified times of the file specified by *path*.
3528
3529 :func:`utime` takes two optional parameters, *times* and *ns*.
3530 These specify the times set on *path* and are used as follows:
3531
3532 - If *ns* is specified,
3533 it must be a 2-tuple of the form ``(atime_ns, mtime_ns)``
3534 where each member is an int expressing nanoseconds.
3535 - If *times* is not ``None``,
3536 it must be a 2-tuple of the form ``(atime, mtime)``
3537 where each member is an int or float expressing seconds.
3538 - If *times* is ``None`` and *ns* is unspecified,
3539 this is equivalent to specifying ``ns=(atime_ns, mtime_ns)``
3540 where both times are the current time.
3541
3542 It is an error to specify tuples for both *times* and *ns*.
3543
3544 Note that the exact times you set here may not be returned by a subsequent
3545 :func:`~os.stat` call, depending on the resolution with which your operating
3546 system records access and modification times; see :func:`~os.stat`. The best
3547 way to preserve exact times is to use the *st_atime_ns* and *st_mtime_ns*
3548 fields from the :func:`os.stat` result object with the *ns* parameter to
3549 :func:`utime`.
3550
3551 This function can support :ref:`specifying a file descriptor <path_fd>`,
3552 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
3553 following symlinks <follow_symlinks>`.
3554
3555 .. audit-event:: os.utime path,times,ns,dir_fd os.utime
3556
3557 .. versionchanged:: 3.3
3558 Added support for specifying *path* as an open file descriptor,
3559 and the *dir_fd*, *follow_symlinks*, and *ns* parameters.
3560
3561 .. versionchanged:: 3.6
3562 Accepts a :term:`path-like object`.
3563
3564
3565 .. function:: walk(top, topdown=True, onerror=None, followlinks=False)
3566
3567 .. index::
3568 single: directory; walking
3569 single: directory; traversal
3570
3571 Generate the file names in a directory tree by walking the tree
3572 either top-down or bottom-up. For each directory in the tree rooted at directory
3573 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
3574 filenames)``.
3575
3576 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
3577 names of the subdirectories in *dirpath* (including symlinks to directories,
3578 and excluding ``'.'`` and ``'..'``).
3579 *filenames* is a list of the names of the non-directory files in *dirpath*.
3580 Note that the names in the lists contain no path components. To get a full path
3581 (which begins with *top*) to a file or directory in *dirpath*, do
3582 ``os.path.join(dirpath, name)``. Whether or not the lists are sorted
3583 depends on the file system. If a file is removed from or added to the
3584 *dirpath* directory during generating the lists, whether a name for that
3585 file be included is unspecified.
3586
3587 If optional argument *topdown* is ``True`` or not specified, the triple for a
3588 directory is generated before the triples for any of its subdirectories
3589 (directories are generated top-down). If *topdown* is ``False``, the triple
3590 for a directory is generated after the triples for all of its subdirectories
3591 (directories are generated bottom-up). No matter the value of *topdown*, the
3592 list of subdirectories is retrieved before the tuples for the directory and
3593 its subdirectories are generated.
3594
3595 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
3596 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
3597 recurse into the subdirectories whose names remain in *dirnames*; this can be
3598 used to prune the search, impose a specific order of visiting, or even to inform
3599 :func:`walk` about directories the caller creates or renames before it resumes
3600 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` has
3601 no effect on the behavior of the walk, because in bottom-up mode the directories
3602 in *dirnames* are generated before *dirpath* itself is generated.
3603
3604 By default, errors from the :func:`scandir` call are ignored. If optional
3605 argument *onerror* is specified, it should be a function; it will be called with
3606 one argument, an :exc:`OSError` instance. It can report the error to continue
3607 with the walk, or raise the exception to abort the walk. Note that the filename
3608 is available as the ``filename`` attribute of the exception object.
3609
3610 By default, :func:`walk` will not walk down into symbolic links that resolve to
3611 directories. Set *followlinks* to ``True`` to visit directories pointed to by
3612 symlinks, on systems that support them.
3613
3614 .. note::
3615
3616 Be aware that setting *followlinks* to ``True`` can lead to infinite
3617 recursion if a link points to a parent directory of itself. :func:`walk`
3618 does not keep track of the directories it visited already.
3619
3620 .. note::
3621
3622 If you pass a relative pathname, don't change the current working directory
3623 between resumptions of :func:`walk`. :func:`walk` never changes the current
3624 directory, and assumes that its caller doesn't either.
3625
3626 This example displays the number of bytes taken by non-directory files in each
3627 directory under the starting directory, except that it doesn't look under any
3628 ``__pycache__`` subdirectory::
3629
3630 import os
3631 from os.path import join, getsize
3632 for root, dirs, files in os.walk('python/Lib/xml'):
3633 print(root, "consumes", end=" ")
3634 print(sum(getsize(join(root, name)) for name in files), end=" ")
3635 print("bytes in", len(files), "non-directory files")
3636 if '__pycache__' in dirs:
3637 dirs.remove('__pycache__') # don't visit __pycache__ directories
3638
3639 In the next example (simple implementation of :func:`shutil.rmtree`),
3640 walking the tree bottom-up is essential, :func:`rmdir` doesn't allow
3641 deleting a directory before the directory is empty::
3642
3643 # Delete everything reachable from the directory named in "top",
3644 # assuming there are no symbolic links.
3645 # CAUTION: This is dangerous! For example, if top == '/', it
3646 # could delete all your disk files.
3647 import os
3648 for root, dirs, files in os.walk(top, topdown=False):
3649 for name in files:
3650 os.remove(os.path.join(root, name))
3651 for name in dirs:
3652 os.rmdir(os.path.join(root, name))
3653 os.rmdir(top)
3654
3655 .. audit-event:: os.walk top,topdown,onerror,followlinks os.walk
3656
3657 .. versionchanged:: 3.5
3658 This function now calls :func:`os.scandir` instead of :func:`os.listdir`,
3659 making it faster by reducing the number of calls to :func:`os.stat`.
3660
3661 .. versionchanged:: 3.6
3662 Accepts a :term:`path-like object`.
3663
3664
3665 .. function:: fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)
3666
3667 .. index::
3668 single: directory; walking
3669 single: directory; traversal
3670
3671 This behaves exactly like :func:`walk`, except that it yields a 4-tuple
3672 ``(dirpath, dirnames, filenames, dirfd)``, and it supports ``dir_fd``.
3673
3674 *dirpath*, *dirnames* and *filenames* are identical to :func:`walk` output,
3675 and *dirfd* is a file descriptor referring to the directory *dirpath*.
3676
3677 This function always supports :ref:`paths relative to directory descriptors
3678 <dir_fd>` and :ref:`not following symlinks <follow_symlinks>`. Note however
3679 that, unlike other functions, the :func:`fwalk` default value for
3680 *follow_symlinks* is ``False``.
3681
3682 .. note::
3683
3684 Since :func:`fwalk` yields file descriptors, those are only valid until
3685 the next iteration step, so you should duplicate them (e.g. with
3686 :func:`dup`) if you want to keep them longer.
3687
3688 This example displays the number of bytes taken by non-directory files in each
3689 directory under the starting directory, except that it doesn't look under any
3690 ``__pycache__`` subdirectory::
3691
3692 import os
3693 for root, dirs, files, rootfd in os.fwalk('python/Lib/xml'):
3694 print(root, "consumes", end=" ")
3695 print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
3696 end=" ")
3697 print("bytes in", len(files), "non-directory files")
3698 if '__pycache__' in dirs:
3699 dirs.remove('__pycache__') # don't visit __pycache__ directories
3700
3701 In the next example, walking the tree bottom-up is essential:
3702 :func:`rmdir` doesn't allow deleting a directory before the directory is
3703 empty::
3704
3705 # Delete everything reachable from the directory named in "top",
3706 # assuming there are no symbolic links.
3707 # CAUTION: This is dangerous! For example, if top == '/', it
3708 # could delete all your disk files.
3709 import os
3710 for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
3711 for name in files:
3712 os.unlink(name, dir_fd=rootfd)
3713 for name in dirs:
3714 os.rmdir(name, dir_fd=rootfd)
3715
3716 .. audit-event:: os.fwalk top,topdown,onerror,follow_symlinks,dir_fd os.fwalk
3717
3718 .. availability:: Unix.
3719
3720 .. versionadded:: 3.3
3721
3722 .. versionchanged:: 3.6
3723 Accepts a :term:`path-like object`.
3724
3725 .. versionchanged:: 3.7
3726 Added support for :class:`bytes` paths.
3727
3728
3729 .. function:: memfd_create(name[, flags=os.MFD_CLOEXEC])
3730
3731 Create an anonymous file and return a file descriptor that refers to it.
3732 *flags* must be one of the ``os.MFD_*`` constants available on the system
3733 (or a bitwise ORed combination of them). By default, the new file
3734 descriptor is :ref:`non-inheritable <fd_inheritance>`.
3735
3736 The name supplied in *name* is used as a filename and will be displayed as
3737 the target of the corresponding symbolic link in the directory
3738 ``/proc/self/fd/``. The displayed name is always prefixed with ``memfd:``
3739 and serves only for debugging purposes. Names do not affect the behavior of
3740 the file descriptor, and as such multiple files can have the same name
3741 without any side effects.
3742
3743 .. availability:: Linux >= 3.17 with glibc >= 2.27.
3744
3745 .. versionadded:: 3.8
3746
3747
3748 .. data:: MFD_CLOEXEC
3749 MFD_ALLOW_SEALING
3750 MFD_HUGETLB
3751 MFD_HUGE_SHIFT
3752 MFD_HUGE_MASK
3753 MFD_HUGE_64KB
3754 MFD_HUGE_512KB
3755 MFD_HUGE_1MB
3756 MFD_HUGE_2MB
3757 MFD_HUGE_8MB
3758 MFD_HUGE_16MB
3759 MFD_HUGE_32MB
3760 MFD_HUGE_256MB
3761 MFD_HUGE_512MB
3762 MFD_HUGE_1GB
3763 MFD_HUGE_2GB
3764 MFD_HUGE_16GB
3765
3766 These flags can be passed to :func:`memfd_create`.
3767
3768 .. availability:: Linux >= 3.17 with glibc >= 2.27
3769
3770 The ``MFD_HUGE*`` flags are only available since Linux 4.14.
3771
3772 .. versionadded:: 3.8
3773
3774
3775 .. function:: eventfd(initval[, flags=os.EFD_CLOEXEC])
3776
3777 Create and return an event file descriptor. The file descriptors supports
3778 raw :func:`read` and :func:`write` with a buffer size of 8,
3779 :func:`~select.select`, :func:`~select.poll` and similar. See man page
3780 :manpage:`eventfd(2)` for more information. By default, the
3781 new file descriptor is :ref:`non-inheritable <fd_inheritance>`.
3782
3783 *initval* is the initial value of the event counter. The initial value
3784 must be a 32 bit unsigned integer. Please note that the initial value is
3785 limited to a 32 bit unsigned int although the event counter is an unsigned
3786 64 bit integer with a maximum value of 2\ :sup:`64`\ -\ 2.
3787
3788 *flags* can be constructed from :const:`EFD_CLOEXEC`,
3789 :const:`EFD_NONBLOCK`, and :const:`EFD_SEMAPHORE`.
3790
3791 If :const:`EFD_SEMAPHORE` is specified and the event counter is non-zero,
3792 :func:`eventfd_read` returns 1 and decrements the counter by one.
3793
3794 If :const:`EFD_SEMAPHORE` is not specified and the event counter is
3795 non-zero, :func:`eventfd_read` returns the current event counter value and
3796 resets the counter to zero.
3797
3798 If the event counter is zero and :const:`EFD_NONBLOCK` is not
3799 specified, :func:`eventfd_read` blocks.
3800
3801 :func:`eventfd_write` increments the event counter. Write blocks if the
3802 write operation would increment the counter to a value larger than
3803 2\ :sup:`64`\ -\ 2.
3804
3805 Example::
3806
3807 import os
3808
3809 # semaphore with start value '1'
3810 fd = os.eventfd(1, os.EFD_SEMAPHORE | os.EFD_CLOEXEC)
3811 try:
3812 # acquire semaphore
3813 v = os.eventfd_read(fd)
3814 try:
3815 do_work()
3816 finally:
3817 # release semaphore
3818 os.eventfd_write(fd, v)
3819 finally:
3820 os.close(fd)
3821
3822 .. availability:: Linux >= 2.6.27 with glibc >= 2.8
3823
3824 .. versionadded:: 3.10
3825
3826 .. function:: eventfd_read(fd)
3827
3828 Read value from an :func:`eventfd` file descriptor and return a 64 bit
3829 unsigned int. The function does not verify that *fd* is an :func:`eventfd`.
3830
3831 .. availability:: Linux >= 2.6.27
3832
3833 .. versionadded:: 3.10
3834
3835 .. function:: eventfd_write(fd, value)
3836
3837 Add value to an :func:`eventfd` file descriptor. *value* must be a 64 bit
3838 unsigned int. The function does not verify that *fd* is an :func:`eventfd`.
3839
3840 .. availability:: Linux >= 2.6.27
3841
3842 .. versionadded:: 3.10
3843
3844 .. data:: EFD_CLOEXEC
3845
3846 Set close-on-exec flag for new :func:`eventfd` file descriptor.
3847
3848 .. availability:: Linux >= 2.6.27
3849
3850 .. versionadded:: 3.10
3851
3852 .. data:: EFD_NONBLOCK
3853
3854 Set :const:`O_NONBLOCK` status flag for new :func:`eventfd` file
3855 descriptor.
3856
3857 .. availability:: Linux >= 2.6.27
3858
3859 .. versionadded:: 3.10
3860
3861 .. data:: EFD_SEMAPHORE
3862
3863 Provide semaphore-like semantics for reads from an :func:`eventfd` file
3864 descriptor. On read the internal counter is decremented by one.
3865
3866 .. availability:: Linux >= 2.6.30
3867
3868 .. versionadded:: 3.10
3869
3870
3871 .. _os-timerfd:
3872
3873 Timer File Descriptors
3874 ~~~~~~~~~~~~~~~~~~~~~~
3875
3876 .. versionadded:: 3.13
3877
3878 These functions provide support for Linux's *timer file descriptor* API.
3879 Naturally, they are all only available on Linux.
3880
3881 .. function:: timerfd_create(clockid, /, *, flags=0)
3882
3883 Create and return a timer file descriptor (*timerfd*).
3884
3885 The file descriptor returned by :func:`timerfd_create` supports:
3886
3887 - :func:`read`
3888 - :func:`~select.select`
3889 - :func:`~select.poll`
3890
3891 The file descriptor's :func:`read` method can be called with a buffer size
3892 of 8. If the timer has already expired one or more times, :func:`read`
3893 returns the number of expirations with the host's endianness, which may be
3894 converted to an :class:`int` by ``int.from_bytes(x, byteorder=sys.byteorder)``.
3895
3896 :func:`~select.select` and :func:`~select.poll` can be used to wait until
3897 timer expires and the file descriptor is readable.
3898
3899 *clockid* must be a valid :ref:`clock ID <time-clock-id-constants>`,
3900 as defined in the :py:mod:`time` module:
3901
3902 - :const:`time.CLOCK_REALTIME`
3903 - :const:`time.CLOCK_MONOTONIC`
3904 - :const:`time.CLOCK_BOOTTIME` (Since Linux 3.15 for timerfd_create)
3905
3906 If *clockid* is :const:`time.CLOCK_REALTIME`, a settable system-wide
3907 real-time clock is used. If system clock is changed, timer setting need
3908 to be updated. To cancel timer when system clock is changed, see
3909 :const:`TFD_TIMER_CANCEL_ON_SET`.
3910
3911 If *clockid* is :const:`time.CLOCK_MONOTONIC`, a non-settable monotonically
3912 increasing clock is used. Even if the system clock is changed, the timer
3913 setting will not be affected.
3914
3915 If *clockid* is :const:`time.CLOCK_BOOTTIME`, same as :const:`time.CLOCK_MONOTONIC`
3916 except it includes any time that the system is suspended.
3917
3918 The file descriptor's behaviour can be modified by specifying a *flags* value.
3919 Any of the following variables may used, combined using bitwise OR
3920 (the ``|`` operator):
3921
3922 - :const:`TFD_NONBLOCK`
3923 - :const:`TFD_CLOEXEC`
3924
3925 If :const:`TFD_NONBLOCK` is not set as a flag, :func:`read` blocks until
3926 the timer expires. If it is set as a flag, :func:`read` doesn't block, but
3927 If there hasn't been an expiration since the last call to read,
3928 :func:`read` raises :class:`OSError` with ``errno`` is set to
3929 :const:`errno.EAGAIN`.
3930
3931 :const:`TFD_CLOEXEC` is always set by Python automatically.
3932
3933 The file descriptor must be closed with :func:`os.close` when it is no
3934 longer needed, or else the file descriptor will be leaked.
3935
3936 .. seealso:: The :manpage:`timerfd_create(2)` man page.
3937
3938 .. availability:: Linux >= 2.6.27 with glibc >= 2.8
3939
3940 .. versionadded:: 3.13
3941
3942
3943 .. function:: timerfd_settime(fd, /, *, flags=flags, initial=0.0, interval=0.0)
3944
3945 Alter a timer file descriptor's internal timer.
3946 This function operates the same interval timer as :func:`timerfd_settime_ns`.
3947
3948 *fd* must be a valid timer file descriptor.
3949
3950 The timer's behaviour can be modified by specifying a *flags* value.
3951 Any of the following variables may used, combined using bitwise OR
3952 (the ``|`` operator):
3953
3954 - :const:`TFD_TIMER_ABSTIME`
3955 - :const:`TFD_TIMER_CANCEL_ON_SET`
3956
3957 The timer is disabled by setting *initial* to zero (``0``).
3958 If *initial* is equal to or greater than zero, the timer is enabled.
3959 If *initial* is less than zero, it raises an :class:`OSError` exception
3960 with ``errno`` set to :const:`errno.EINVAL`
3961
3962 By default the timer will fire when *initial* seconds have elapsed.
3963 (If *initial* is zero, timer will fire immediately.)
3964
3965 However, if the :const:`TFD_TIMER_ABSTIME` flag is set,
3966 the timer will fire when the timer's clock
3967 (set by *clockid* in :func:`timerfd_create`) reaches *initial* seconds.
3968
3969 The timer's interval is set by the *interval* :py:class:`float`.
3970 If *interval* is zero, the timer only fires once, on the initial expiration.
3971 If *interval* is greater than zero, the timer fires every time *interval*
3972 seconds have elapsed since the previous expiration.
3973 If *interval* is less than zero, it raises :class:`OSError` with ``errno``
3974 set to :const:`errno.EINVAL`
3975
3976 If the :const:`TFD_TIMER_CANCEL_ON_SET` flag is set along with
3977 :const:`TFD_TIMER_ABSTIME` and the clock for this timer is
3978 :const:`time.CLOCK_REALTIME`, the timer is marked as cancelable if the
3979 real-time clock is changed discontinuously. Reading the descriptor is
3980 aborted with the error ECANCELED.
3981
3982 Linux manages system clock as UTC. A daylight-savings time transition is
3983 done by changing time offset only and doesn't cause discontinuous system
3984 clock change.
3985
3986 Discontinuous system clock change will be caused by the following events:
3987
3988 - ``settimeofday``
3989 - ``clock_settime``
3990 - set the system date and time by ``date`` command
3991
3992 Return a two-item tuple of (``next_expiration``, ``interval``) from
3993 the previous timer state, before this function executed.
3994
3995 .. seealso::
3996
3997 :manpage:`timerfd_create(2)`, :manpage:`timerfd_settime(2)`,
3998 :manpage:`settimeofday(2)`, :manpage:`clock_settime(2)`,
3999 and :manpage:`date(1)`.
4000
4001 .. availability:: Linux >= 2.6.27 with glibc >= 2.8
4002
4003 .. versionadded:: 3.13
4004
4005
4006 .. function:: timerfd_settime_ns(fd, /, *, flags=0, initial=0, interval=0)
4007
4008 Similar to :func:`timerfd_settime`, but use time as nanoseconds.
4009 This function operates the same interval timer as :func:`timerfd_settime`.
4010
4011 .. availability:: Linux >= 2.6.27 with glibc >= 2.8
4012
4013 .. versionadded:: 3.13
4014
4015
4016 .. function:: timerfd_gettime(fd, /)
4017
4018 Return a two-item tuple of floats (``next_expiration``, ``interval``).
4019
4020 ``next_expiration`` denotes the relative time until next the timer next fires,
4021 regardless of if the :const:`TFD_TIMER_ABSTIME` flag is set.
4022
4023 ``interval`` denotes the timer's interval.
4024 If zero, the timer will only fire once, after ``next_expiration`` seconds
4025 have elapsed.
4026
4027 .. seealso:: :manpage:`timerfd_gettime(2)`
4028
4029 .. availability:: Linux >= 2.6.27 with glibc >= 2.8
4030
4031 .. versionadded:: 3.13
4032
4033
4034 .. function:: timerfd_gettime_ns(fd, /)
4035
4036 Similar to :func:`timerfd_gettime`, but return time as nanoseconds.
4037
4038 .. availability:: Linux >= 2.6.27 with glibc >= 2.8
4039
4040 .. versionadded:: 3.13
4041
4042 .. data:: TFD_NONBLOCK
4043
4044 A flag for the :func:`timerfd_create` function,
4045 which sets the :const:`O_NONBLOCK` status flag for the new timer file
4046 descriptor. If :const:`TFD_NONBLOCK` is not set as a flag, :func:`read` blocks.
4047
4048 .. availability:: Linux >= 2.6.27 with glibc >= 2.8
4049
4050 .. versionadded:: 3.13
4051
4052 .. data:: TFD_CLOEXEC
4053
4054 A flag for the :func:`timerfd_create` function,
4055 If :const:`TFD_CLOEXEC` is set as a flag, set close-on-exec flag for new file
4056 descriptor.
4057
4058 .. availability:: Linux >= 2.6.27 with glibc >= 2.8
4059
4060 .. versionadded:: 3.13
4061
4062 .. data:: TFD_TIMER_ABSTIME
4063
4064 A flag for the :func:`timerfd_settime` and :func:`timerfd_settime_ns` functions.
4065 If this flag is set, *initial* is interpreted as an absolute value on the
4066 timer's clock (in UTC seconds or nanoseconds since the Unix Epoch).
4067
4068 .. availability:: Linux >= 2.6.27 with glibc >= 2.8
4069
4070 .. versionadded:: 3.13
4071
4072 .. data:: TFD_TIMER_CANCEL_ON_SET
4073
4074 A flag for the :func:`timerfd_settime` and :func:`timerfd_settime_ns`
4075 functions along with :const:`TFD_TIMER_ABSTIME`.
4076 The timer is cancelled when the time of the underlying clock changes
4077 discontinuously.
4078
4079 .. availability:: Linux >= 2.6.27 with glibc >= 2.8
4080
4081 .. versionadded:: 3.13
4082
4083
4084 Linux extended attributes
4085 ~~~~~~~~~~~~~~~~~~~~~~~~~
4086
4087 .. versionadded:: 3.3
4088
4089 These functions are all available on Linux only.
4090
4091 .. function:: getxattr(path, attribute, *, follow_symlinks=True)
4092
4093 Return the value of the extended filesystem attribute *attribute* for
4094 *path*. *attribute* can be bytes or str (directly or indirectly through the
4095 :class:`PathLike` interface). If it is str, it is encoded with the filesystem
4096 encoding.
4097
4098 This function can support :ref:`specifying a file descriptor <path_fd>` and
4099 :ref:`not following symlinks <follow_symlinks>`.
4100
4101 .. audit-event:: os.getxattr path,attribute os.getxattr
4102
4103 .. versionchanged:: 3.6
4104 Accepts a :term:`path-like object` for *path* and *attribute*.
4105
4106
4107 .. function:: listxattr(path=None, *, follow_symlinks=True)
4108
4109 Return a list of the extended filesystem attributes on *path*. The
4110 attributes in the list are represented as strings decoded with the filesystem
4111 encoding. If *path* is ``None``, :func:`listxattr` will examine the current
4112 directory.
4113
4114 This function can support :ref:`specifying a file descriptor <path_fd>` and
4115 :ref:`not following symlinks <follow_symlinks>`.
4116
4117 .. audit-event:: os.listxattr path os.listxattr
4118
4119 .. versionchanged:: 3.6
4120 Accepts a :term:`path-like object`.
4121
4122
4123 .. function:: removexattr(path, attribute, *, follow_symlinks=True)
4124
4125 Removes the extended filesystem attribute *attribute* from *path*.
4126 *attribute* should be bytes or str (directly or indirectly through the
4127 :class:`PathLike` interface). If it is a string, it is encoded
4128 with the :term:`filesystem encoding and error handler`.
4129
4130 This function can support :ref:`specifying a file descriptor <path_fd>` and
4131 :ref:`not following symlinks <follow_symlinks>`.
4132
4133 .. audit-event:: os.removexattr path,attribute os.removexattr
4134
4135 .. versionchanged:: 3.6
4136 Accepts a :term:`path-like object` for *path* and *attribute*.
4137
4138
4139 .. function:: setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)
4140
4141 Set the extended filesystem attribute *attribute* on *path* to *value*.
4142 *attribute* must be a bytes or str with no embedded NULs (directly or
4143 indirectly through the :class:`PathLike` interface). If it is a str,
4144 it is encoded with the :term:`filesystem encoding and error handler`. *flags* may be
4145 :data:`XATTR_REPLACE` or :data:`XATTR_CREATE`. If :data:`XATTR_REPLACE` is
4146 given and the attribute does not exist, ``ENODATA`` will be raised.
4147 If :data:`XATTR_CREATE` is given and the attribute already exists, the
4148 attribute will not be created and ``EEXISTS`` will be raised.
4149
4150 This function can support :ref:`specifying a file descriptor <path_fd>` and
4151 :ref:`not following symlinks <follow_symlinks>`.
4152
4153 .. note::
4154
4155 A bug in Linux kernel versions less than 2.6.39 caused the flags argument
4156 to be ignored on some filesystems.
4157
4158 .. audit-event:: os.setxattr path,attribute,value,flags os.setxattr
4159
4160 .. versionchanged:: 3.6
4161 Accepts a :term:`path-like object` for *path* and *attribute*.
4162
4163
4164 .. data:: XATTR_SIZE_MAX
4165
4166 The maximum size the value of an extended attribute can be. Currently, this
4167 is 64 KiB on Linux.
4168
4169
4170 .. data:: XATTR_CREATE
4171
4172 This is a possible value for the flags argument in :func:`setxattr`. It
4173 indicates the operation must create an attribute.
4174
4175
4176 .. data:: XATTR_REPLACE
4177
4178 This is a possible value for the flags argument in :func:`setxattr`. It
4179 indicates the operation must replace an existing attribute.
4180
4181
4182 .. _os-process:
4183
4184 Process Management
4185 ------------------
4186
4187 These functions may be used to create and manage processes.
4188
4189 The various :func:`exec\* <execl>` functions take a list of arguments for the new
4190 program loaded into the process. In each case, the first of these arguments is
4191 passed to the new program as its own name rather than as an argument a user may
4192 have typed on a command line. For the C programmer, this is the ``argv[0]``
4193 passed to a program's :c:func:`main`. For example, ``os.execv('/bin/echo',
4194 ['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
4195 to be ignored.
4196
4197
4198 .. function:: abort()
4199
4200 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
4201 behavior is to produce a core dump; on Windows, the process immediately returns
4202 an exit code of ``3``. Be aware that calling this function will not call the
4203 Python signal handler registered for :const:`SIGABRT` with
4204 :func:`signal.signal`.
4205
4206
4207 .. function:: add_dll_directory(path)
4208
4209 Add a path to the DLL search path.
4210
4211 This search path is used when resolving dependencies for imported
4212 extension modules (the module itself is resolved through
4213 :data:`sys.path`), and also by :mod:`ctypes`.
4214
4215 Remove the directory by calling **close()** on the returned object
4216 or using it in a :keyword:`with` statement.
4217
4218 See the `Microsoft documentation
4219 <https://msdn.microsoft.com/44228cf2-6306-466c-8f16-f513cd3ba8b5>`_
4220 for more information about how DLLs are loaded.
4221
4222 .. audit-event:: os.add_dll_directory path os.add_dll_directory
4223
4224 .. availability:: Windows.
4225
4226 .. versionadded:: 3.8
4227 Previous versions of CPython would resolve DLLs using the default
4228 behavior for the current process. This led to inconsistencies,
4229 such as only sometimes searching :envvar:`PATH` or the current
4230 working directory, and OS functions such as ``AddDllDirectory``
4231 having no effect.
4232
4233 In 3.8, the two primary ways DLLs are loaded now explicitly
4234 override the process-wide behavior to ensure consistency. See the
4235 :ref:`porting notes <bpo-36085-whatsnew>` for information on
4236 updating libraries.
4237
4238
4239 .. function:: execl(path, arg0, arg1, ...)
4240 execle(path, arg0, arg1, ..., env)
4241 execlp(file, arg0, arg1, ...)
4242 execlpe(file, arg0, arg1, ..., env)
4243 execv(path, args)
4244 execve(path, args, env)
4245 execvp(file, args)
4246 execvpe(file, args, env)
4247
4248 These functions all execute a new program, replacing the current process; they
4249 do not return. On Unix, the new executable is loaded into the current process,
4250 and will have the same process id as the caller. Errors will be reported as
4251 :exc:`OSError` exceptions.
4252
4253 The current process is replaced immediately. Open file objects and
4254 descriptors are not flushed, so if there may be data buffered
4255 on these open files, you should flush them using
4256 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
4257 :func:`exec\* <execl>` function.
4258
4259 The "l" and "v" variants of the :func:`exec\* <execl>` functions differ in how
4260 command-line arguments are passed. The "l" variants are perhaps the easiest
4261 to work with if the number of parameters is fixed when the code is written; the
4262 individual parameters simply become additional parameters to the :func:`!execl\*`
4263 functions. The "v" variants are good when the number of parameters is
4264 variable, with the arguments being passed in a list or tuple as the *args*
4265 parameter. In either case, the arguments to the child process should start with
4266 the name of the command being run, but this is not enforced.
4267
4268 The variants which include a "p" near the end (:func:`execlp`,
4269 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
4270 :envvar:`PATH` environment variable to locate the program *file*. When the
4271 environment is being replaced (using one of the :func:`exec\*e <execl>` variants,
4272 discussed in the next paragraph), the new environment is used as the source of
4273 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
4274 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
4275 locate the executable; *path* must contain an appropriate absolute or relative
4276 path. Relative paths must include at least one slash, even on Windows, as
4277 plain names will not be resolved.
4278
4279 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
4280 that these all end in "e"), the *env* parameter must be a mapping which is
4281 used to define the environment variables for the new process (these are used
4282 instead of the current process' environment); the functions :func:`execl`,
4283 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
4284 inherit the environment of the current process.
4285
4286 For :func:`execve` on some platforms, *path* may also be specified as an open
4287 file descriptor. This functionality may not be supported on your platform;
4288 you can check whether or not it is available using :data:`os.supports_fd`.
4289 If it is unavailable, using it will raise a :exc:`NotImplementedError`.
4290
4291 .. audit-event:: os.exec path,args,env os.execl
4292
4293 .. availability:: Unix, Windows, not WASI, not Android, not iOS.
4294
4295 .. versionchanged:: 3.3
4296 Added support for specifying *path* as an open file descriptor
4297 for :func:`execve`.
4298
4299 .. versionchanged:: 3.6
4300 Accepts a :term:`path-like object`.
4301
4302 .. function:: _exit(n)
4303
4304 Exit the process with status *n*, without calling cleanup handlers, flushing
4305 stdio buffers, etc.
4306
4307 .. note::
4308
4309 The standard way to exit is :func:`sys.exit(n) <sys.exit>`. :func:`!_exit` should
4310 normally only be used in the child process after a :func:`fork`.
4311
4312 The following exit codes are defined and can be used with :func:`_exit`,
4313 although they are not required. These are typically used for system programs
4314 written in Python, such as a mail server's external command delivery program.
4315
4316 .. note::
4317
4318 Some of these may not be available on all Unix platforms, since there is some
4319 variation. These constants are defined where they are defined by the underlying
4320 platform.
4321
4322
4323 .. data:: EX_OK
4324
4325 Exit code that means no error occurred. May be taken from the defined value of
4326 ``EXIT_SUCCESS`` on some platforms. Generally has a value of zero.
4327
4328 .. availability:: Unix, Windows.
4329
4330
4331 .. data:: EX_USAGE
4332
4333 Exit code that means the command was used incorrectly, such as when the wrong
4334 number of arguments are given.
4335
4336 .. availability:: Unix, not WASI.
4337
4338
4339 .. data:: EX_DATAERR
4340
4341 Exit code that means the input data was incorrect.
4342
4343 .. availability:: Unix, not WASI.
4344
4345
4346 .. data:: EX_NOINPUT
4347
4348 Exit code that means an input file did not exist or was not readable.
4349
4350 .. availability:: Unix, not WASI.
4351
4352
4353 .. data:: EX_NOUSER
4354
4355 Exit code that means a specified user did not exist.
4356
4357 .. availability:: Unix, not WASI.
4358
4359
4360 .. data:: EX_NOHOST
4361
4362 Exit code that means a specified host did not exist.
4363
4364 .. availability:: Unix, not WASI.
4365
4366
4367 .. data:: EX_UNAVAILABLE
4368
4369 Exit code that means that a required service is unavailable.
4370
4371 .. availability:: Unix, not WASI.
4372
4373
4374 .. data:: EX_SOFTWARE
4375
4376 Exit code that means an internal software error was detected.
4377
4378 .. availability:: Unix, not WASI.
4379
4380
4381 .. data:: EX_OSERR
4382
4383 Exit code that means an operating system error was detected, such as the
4384 inability to fork or create a pipe.
4385
4386 .. availability:: Unix, not WASI.
4387
4388
4389 .. data:: EX_OSFILE
4390
4391 Exit code that means some system file did not exist, could not be opened, or had
4392 some other kind of error.
4393
4394 .. availability:: Unix, not WASI.
4395
4396
4397 .. data:: EX_CANTCREAT
4398
4399 Exit code that means a user specified output file could not be created.
4400
4401 .. availability:: Unix, not WASI.
4402
4403
4404 .. data:: EX_IOERR
4405
4406 Exit code that means that an error occurred while doing I/O on some file.
4407
4408 .. availability:: Unix, not WASI.
4409
4410
4411 .. data:: EX_TEMPFAIL
4412
4413 Exit code that means a temporary failure occurred. This indicates something
4414 that may not really be an error, such as a network connection that couldn't be
4415 made during a retryable operation.
4416
4417 .. availability:: Unix, not WASI.
4418
4419
4420 .. data:: EX_PROTOCOL
4421
4422 Exit code that means that a protocol exchange was illegal, invalid, or not
4423 understood.
4424
4425 .. availability:: Unix, not WASI.
4426
4427
4428 .. data:: EX_NOPERM
4429
4430 Exit code that means that there were insufficient permissions to perform the
4431 operation (but not intended for file system problems).
4432
4433 .. availability:: Unix, not WASI.
4434
4435
4436 .. data:: EX_CONFIG
4437
4438 Exit code that means that some kind of configuration error occurred.
4439
4440 .. availability:: Unix, not WASI.
4441
4442
4443 .. data:: EX_NOTFOUND
4444
4445 Exit code that means something like "an entry was not found".
4446
4447 .. availability:: Unix, not WASI.
4448
4449
4450 .. function:: fork()
4451
4452 Fork a child process. Return ``0`` in the child and the child's process id in the
4453 parent. If an error occurs :exc:`OSError` is raised.
4454
4455 Note that some platforms including FreeBSD <= 6.3 and Cygwin have
4456 known issues when using ``fork()`` from a thread.
4457
4458 .. audit-event:: os.fork "" os.fork
4459
4460 .. warning::
4461
4462 If you use TLS sockets in an application calling ``fork()``, see
4463 the warning in the :mod:`ssl` documentation.
4464
4465 .. warning::
4466
4467 On macOS the use of this function is unsafe when mixed with using
4468 higher-level system APIs, and that includes using :mod:`urllib.request`.
4469
4470 .. versionchanged:: 3.8
4471 Calling ``fork()`` in a subinterpreter is no longer supported
4472 (:exc:`RuntimeError` is raised).
4473
4474 .. versionchanged:: 3.12
4475 If Python is able to detect that your process has multiple
4476 threads, :func:`os.fork` now raises a :exc:`DeprecationWarning`.
4477
4478 We chose to surface this as a warning, when detectable, to better
4479 inform developers of a design problem that the POSIX platform
4480 specifically notes as not supported. Even in code that
4481 *appears* to work, it has never been safe to mix threading with
4482 :func:`os.fork` on POSIX platforms. The CPython runtime itself has
4483 always made API calls that are not safe for use in the child
4484 process when threads existed in the parent (such as ``malloc`` and
4485 ``free``).
4486
4487 Users of macOS or users of libc or malloc implementations other
4488 than those typically found in glibc to date are among those
4489 already more likely to experience deadlocks running such code.
4490
4491 See `this discussion on fork being incompatible with threads
4492 <https://discuss.python.org/t/33555>`_
4493 for technical details of why we're surfacing this longstanding
4494 platform compatibility problem to developers.
4495
4496 .. availability:: POSIX, not WASI, not Android, not iOS.
4497
4498
4499 .. function:: forkpty()
4500
4501 Fork a child process, using a new pseudo-terminal as the child's controlling
4502 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
4503 new child's process id in the parent, and *fd* is the file descriptor of the
4504 master end of the pseudo-terminal. For a more portable approach, use the
4505 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
4506
4507 .. audit-event:: os.forkpty "" os.forkpty
4508
4509 .. warning::
4510
4511 On macOS the use of this function is unsafe when mixed with using
4512 higher-level system APIs, and that includes using :mod:`urllib.request`.
4513
4514 .. versionchanged:: 3.8
4515 Calling ``forkpty()`` in a subinterpreter is no longer supported
4516 (:exc:`RuntimeError` is raised).
4517
4518 .. versionchanged:: 3.12
4519 If Python is able to detect that your process has multiple
4520 threads, this now raises a :exc:`DeprecationWarning`. See the
4521 longer explanation on :func:`os.fork`.
4522
4523 .. availability:: Unix, not WASI, not Android, not iOS.
4524
4525
4526 .. function:: kill(pid, sig, /)
4527
4528 .. index::
4529 single: process; killing
4530 single: process; signalling
4531
4532 Send signal *sig* to the process *pid*. Constants for the specific signals
4533 available on the host platform are defined in the :mod:`signal` module.
4534
4535 Windows: The :const:`signal.CTRL_C_EVENT` and
4536 :const:`signal.CTRL_BREAK_EVENT` signals are special signals which can
4537 only be sent to console processes which share a common console window,
4538 e.g., some subprocesses. Any other value for *sig* will cause the process
4539 to be unconditionally killed by the TerminateProcess API, and the exit code
4540 will be set to *sig*.
4541
4542 See also :func:`signal.pthread_kill`.
4543
4544 .. audit-event:: os.kill pid,sig os.kill
4545
4546 .. availability:: Unix, Windows, not WASI, not iOS.
4547
4548 .. versionchanged:: 3.2
4549 Added Windows support.
4550
4551
4552 .. function:: killpg(pgid, sig, /)
4553
4554 .. index::
4555 single: process; killing
4556 single: process; signalling
4557
4558 Send the signal *sig* to the process group *pgid*.
4559
4560 .. audit-event:: os.killpg pgid,sig os.killpg
4561
4562 .. availability:: Unix, not WASI, not iOS.
4563
4564
4565 .. function:: nice(increment, /)
4566
4567 Add *increment* to the process's "niceness". Return the new niceness.
4568
4569 .. availability:: Unix, not WASI.
4570
4571
4572 .. function:: pidfd_open(pid, flags=0)
4573
4574 Return a file descriptor referring to the process *pid* with *flags* set.
4575 This descriptor can be used to perform process management without races
4576 and signals.
4577
4578 See the :manpage:`pidfd_open(2)` man page for more details.
4579
4580 .. availability:: Linux >= 5.3, Android >= :func:`build-time <sys.getandroidapilevel>` API level 31
4581 .. versionadded:: 3.9
4582
4583 .. data:: PIDFD_NONBLOCK
4584
4585 This flag indicates that the file descriptor will be non-blocking.
4586 If the process referred to by the file descriptor has not yet terminated,
4587 then an attempt to wait on the file descriptor using :manpage:`waitid(2)`
4588 will immediately return the error :const:`~errno.EAGAIN` rather than blocking.
4589
4590 .. availability:: Linux >= 5.10
4591 .. versionadded:: 3.12
4592
4593
4594 .. function:: plock(op, /)
4595
4596 Lock program segments into memory. The value of *op* (defined in
4597 ``<sys/lock.h>``) determines which segments are locked.
4598
4599 .. availability:: Unix, not WASI, not iOS.
4600
4601
4602 .. function:: popen(cmd, mode='r', buffering=-1)
4603
4604 Open a pipe to or from command *cmd*.
4605 The return value is an open file object
4606 connected to the pipe, which can be read or written depending on whether *mode*
4607 is ``'r'`` (default) or ``'w'``.
4608 The *buffering* argument have the same meaning as
4609 the corresponding argument to the built-in :func:`open` function. The
4610 returned file object reads or writes text strings rather than bytes.
4611
4612 The ``close`` method returns :const:`None` if the subprocess exited
4613 successfully, or the subprocess's return code if there was an
4614 error. On POSIX systems, if the return code is positive it
4615 represents the return value of the process left-shifted by one
4616 byte. If the return code is negative, the process was terminated
4617 by the signal given by the negated value of the return code. (For
4618 example, the return value might be ``- signal.SIGKILL`` if the
4619 subprocess was killed.) On Windows systems, the return value
4620 contains the signed integer return code from the child process.
4621
4622 On Unix, :func:`waitstatus_to_exitcode` can be used to convert the ``close``
4623 method result (exit status) into an exit code if it is not ``None``. On
4624 Windows, the ``close`` method result is directly the exit code
4625 (or ``None``).
4626
4627 This is implemented using :class:`subprocess.Popen`; see that class's
4628 documentation for more powerful ways to manage and communicate with
4629 subprocesses.
4630
4631 .. availability:: not WASI, not Android, not iOS.
4632
4633 .. note::
4634 The :ref:`Python UTF-8 Mode <utf8-mode>` affects encodings used
4635 for *cmd* and pipe contents.
4636
4637 :func:`popen` is a simple wrapper around :class:`subprocess.Popen`.
4638 Use :class:`subprocess.Popen` or :func:`subprocess.run` to
4639 control options like encodings.
4640
4641
4642 .. function:: posix_spawn(path, argv, env, *, file_actions=None, \
4643 setpgroup=None, resetids=False, setsid=False, setsigmask=(), \
4644 setsigdef=(), scheduler=None)
4645
4646 Wraps the :c:func:`!posix_spawn` C library API for use from Python.
4647
4648 Most users should use :func:`subprocess.run` instead of :func:`posix_spawn`.
4649
4650 The positional-only arguments *path*, *args*, and *env* are similar to
4651 :func:`execve`. *env* is allowed to be ``None``, in which case current
4652 process' environment is used.
4653
4654 The *path* parameter is the path to the executable file. The *path* should
4655 contain a directory. Use :func:`posix_spawnp` to pass an executable file
4656 without directory.
4657
4658 The *file_actions* argument may be a sequence of tuples describing actions
4659 to take on specific file descriptors in the child process between the C
4660 library implementation's :c:func:`fork` and :c:func:`exec` steps.
4661 The first item in each tuple must be one of the three type indicator
4662 listed below describing the remaining tuple elements:
4663
4664 .. data:: POSIX_SPAWN_OPEN
4665
4666 (``os.POSIX_SPAWN_OPEN``, *fd*, *path*, *flags*, *mode*)
4667
4668 Performs ``os.dup2(os.open(path, flags, mode), fd)``.
4669
4670 .. data:: POSIX_SPAWN_CLOSE
4671
4672 (``os.POSIX_SPAWN_CLOSE``, *fd*)
4673
4674 Performs ``os.close(fd)``.
4675
4676 .. data:: POSIX_SPAWN_DUP2
4677
4678 (``os.POSIX_SPAWN_DUP2``, *fd*, *new_fd*)
4679
4680 Performs ``os.dup2(fd, new_fd)``.
4681
4682 .. data:: POSIX_SPAWN_CLOSEFROM
4683
4684 (``os.POSIX_SPAWN_CLOSEFROM``, *fd*)
4685
4686 Performs ``os.closerange(fd, INF)``.
4687
4688 These tuples correspond to the C library
4689 :c:func:`!posix_spawn_file_actions_addopen`,
4690 :c:func:`!posix_spawn_file_actions_addclose`,
4691 :c:func:`!posix_spawn_file_actions_adddup2`, and
4692 :c:func:`!posix_spawn_file_actions_addclosefrom_np` API calls used to prepare
4693 for the :c:func:`!posix_spawn` call itself.
4694
4695 The *setpgroup* argument will set the process group of the child to the value
4696 specified. If the value specified is 0, the child's process group ID will be
4697 made the same as its process ID. If the value of *setpgroup* is not set, the
4698 child will inherit the parent's process group ID. This argument corresponds
4699 to the C library :c:macro:`!POSIX_SPAWN_SETPGROUP` flag.
4700
4701 If the *resetids* argument is ``True`` it will reset the effective UID and
4702 GID of the child to the real UID and GID of the parent process. If the
4703 argument is ``False``, then the child retains the effective UID and GID of
4704 the parent. In either case, if the set-user-ID and set-group-ID permission
4705 bits are enabled on the executable file, their effect will override the
4706 setting of the effective UID and GID. This argument corresponds to the C
4707 library :c:macro:`!POSIX_SPAWN_RESETIDS` flag.
4708
4709 If the *setsid* argument is ``True``, it will create a new session ID
4710 for ``posix_spawn``. *setsid* requires :c:macro:`!POSIX_SPAWN_SETSID`
4711 or :c:macro:`!POSIX_SPAWN_SETSID_NP` flag. Otherwise, :exc:`NotImplementedError`
4712 is raised.
4713
4714 The *setsigmask* argument will set the signal mask to the signal set
4715 specified. If the parameter is not used, then the child inherits the
4716 parent's signal mask. This argument corresponds to the C library
4717 :c:macro:`!POSIX_SPAWN_SETSIGMASK` flag.
4718
4719 The *sigdef* argument will reset the disposition of all signals in the set
4720 specified. This argument corresponds to the C library
4721 :c:macro:`!POSIX_SPAWN_SETSIGDEF` flag.
4722
4723 The *scheduler* argument must be a tuple containing the (optional) scheduler
4724 policy and an instance of :class:`sched_param` with the scheduler parameters.
4725 A value of ``None`` in the place of the scheduler policy indicates that is
4726 not being provided. This argument is a combination of the C library
4727 :c:macro:`!POSIX_SPAWN_SETSCHEDPARAM` and :c:macro:`!POSIX_SPAWN_SETSCHEDULER`
4728 flags.
4729
4730 .. audit-event:: os.posix_spawn path,argv,env os.posix_spawn
4731
4732 .. versionadded:: 3.8
4733
4734 .. versionchanged:: 3.13
4735 *env* parameter accepts ``None``.
4736 ``os.POSIX_SPAWN_CLOSEFROM`` is available on platforms where
4737 :c:func:`!posix_spawn_file_actions_addclosefrom_np` exists.
4738
4739 .. availability:: Unix, not WASI, not Android, not iOS.
4740
4741 .. function:: posix_spawnp(path, argv, env, *, file_actions=None, \
4742 setpgroup=None, resetids=False, setsid=False, setsigmask=(), \
4743 setsigdef=(), scheduler=None)
4744
4745 Wraps the :c:func:`!posix_spawnp` C library API for use from Python.
4746
4747 Similar to :func:`posix_spawn` except that the system searches
4748 for the *executable* file in the list of directories specified by the
4749 :envvar:`PATH` environment variable (in the same way as for ``execvp(3)``).
4750
4751 .. audit-event:: os.posix_spawn path,argv,env os.posix_spawnp
4752
4753 .. versionadded:: 3.8
4754
4755 .. availability:: POSIX, not WASI, not Android, not iOS.
4756
4757 See :func:`posix_spawn` documentation.
4758
4759
4760 .. function:: register_at_fork(*, before=None, after_in_parent=None, \
4761 after_in_child=None)
4762
4763 Register callables to be executed when a new child process is forked
4764 using :func:`os.fork` or similar process cloning APIs.
4765 The parameters are optional and keyword-only.
4766 Each specifies a different call point.
4767
4768 * *before* is a function called before forking a child process.
4769 * *after_in_parent* is a function called from the parent process
4770 after forking a child process.
4771 * *after_in_child* is a function called from the child process.
4772
4773 These calls are only made if control is expected to return to the
4774 Python interpreter. A typical :mod:`subprocess` launch will not
4775 trigger them as the child is not going to re-enter the interpreter.
4776
4777 Functions registered for execution before forking are called in
4778 reverse registration order. Functions registered for execution
4779 after forking (either in the parent or in the child) are called
4780 in registration order.
4781
4782 Note that :c:func:`fork` calls made by third-party C code may not
4783 call those functions, unless it explicitly calls :c:func:`PyOS_BeforeFork`,
4784 :c:func:`PyOS_AfterFork_Parent` and :c:func:`PyOS_AfterFork_Child`.
4785
4786 There is no way to unregister a function.
4787
4788 .. availability:: Unix, not WASI, not Android, not iOS.
4789
4790 .. versionadded:: 3.7
4791
4792
4793 .. function:: spawnl(mode, path, ...)
4794 spawnle(mode, path, ..., env)
4795 spawnlp(mode, file, ...)
4796 spawnlpe(mode, file, ..., env)
4797 spawnv(mode, path, args)
4798 spawnve(mode, path, args, env)
4799 spawnvp(mode, file, args)
4800 spawnvpe(mode, file, args, env)
4801
4802 Execute the program *path* in a new process.
4803
4804 (Note that the :mod:`subprocess` module provides more powerful facilities for
4805 spawning new processes and retrieving their results; using that module is
4806 preferable to using these functions. Check especially the
4807 :ref:`subprocess-replacements` section.)
4808
4809 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
4810 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
4811 exits normally, or ``-signal``, where *signal* is the signal that killed the
4812 process. On Windows, the process id will actually be the process handle, so can
4813 be used with the :func:`waitpid` function.
4814
4815 Note on VxWorks, this function doesn't return ``-signal`` when the new process is
4816 killed. Instead it raises OSError exception.
4817
4818 The "l" and "v" variants of the :func:`spawn\* <spawnl>` functions differ in how
4819 command-line arguments are passed. The "l" variants are perhaps the easiest
4820 to work with if the number of parameters is fixed when the code is written; the
4821 individual parameters simply become additional parameters to the
4822 :func:`!spawnl\*` functions. The "v" variants are good when the number of
4823 parameters is variable, with the arguments being passed in a list or tuple as
4824 the *args* parameter. In either case, the arguments to the child process must
4825 start with the name of the command being run.
4826
4827 The variants which include a second "p" near the end (:func:`spawnlp`,
4828 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
4829 :envvar:`PATH` environment variable to locate the program *file*. When the
4830 environment is being replaced (using one of the :func:`spawn\*e <spawnl>` variants,
4831 discussed in the next paragraph), the new environment is used as the source of
4832 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
4833 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
4834 :envvar:`PATH` variable to locate the executable; *path* must contain an
4835 appropriate absolute or relative path.
4836
4837 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
4838 (note that these all end in "e"), the *env* parameter must be a mapping
4839 which is used to define the environment variables for the new process (they are
4840 used instead of the current process' environment); the functions
4841 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
4842 the new process to inherit the environment of the current process. Note that
4843 keys and values in the *env* dictionary must be strings; invalid keys or
4844 values will cause the function to fail, with a return value of ``127``.
4845
4846 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
4847 equivalent::
4848
4849 import os
4850 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
4851
4852 L = ['cp', 'index.html', '/dev/null']
4853 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
4854
4855 .. audit-event:: os.spawn mode,path,args,env os.spawnl
4856
4857 .. availability:: Unix, Windows, not WASI, not Android, not iOS.
4858
4859 :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
4860 and :func:`spawnvpe` are not available on Windows. :func:`spawnle` and
4861 :func:`spawnve` are not thread-safe on Windows; we advise you to use the
4862 :mod:`subprocess` module instead.
4863
4864 .. versionchanged:: 3.6
4865 Accepts a :term:`path-like object`.
4866
4867
4868 .. data:: P_NOWAIT
4869 P_NOWAITO
4870
4871 Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
4872 functions. If either of these values is given, the :func:`spawn\* <spawnl>` functions
4873 will return as soon as the new process has been created, with the process id as
4874 the return value.
4875
4876 .. availability:: Unix, Windows.
4877
4878
4879 .. data:: P_WAIT
4880
4881 Possible value for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
4882 functions. If this is given as *mode*, the :func:`spawn\* <spawnl>` functions will not
4883 return until the new process has run to completion and will return the exit code
4884 of the process the run is successful, or ``-signal`` if a signal kills the
4885 process.
4886
4887 .. availability:: Unix, Windows.
4888
4889
4890 .. data:: P_DETACH
4891 P_OVERLAY
4892
4893 Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
4894 functions. These are less portable than those listed above. :const:`P_DETACH`
4895 is similar to :const:`P_NOWAIT`, but the new process is detached from the
4896 console of the calling process. If :const:`P_OVERLAY` is used, the current
4897 process will be replaced; the :func:`spawn\* <spawnl>` function will not return.
4898
4899 .. availability:: Windows.
4900
4901
4902 .. function:: startfile(path, [operation], [arguments], [cwd], [show_cmd])
4903
4904 Start a file with its associated application.
4905
4906 When *operation* is not specified, this acts like double-clicking
4907 the file in Windows Explorer, or giving the file name as an argument to the
4908 :program:`start` command from the interactive command shell: the file is opened
4909 with whatever application (if any) its extension is associated.
4910
4911 When another *operation* is given, it must be a "command verb" that specifies
4912 what should be done with the file. Common verbs documented by Microsoft are ``'open'``,
4913 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
4914 ``'find'`` (to be used on directories).
4915
4916 When launching an application, specify *arguments* to be passed as a single
4917 string. This argument may have no effect when using this function to launch a
4918 document.
4919
4920 The default working directory is inherited, but may be overridden by the *cwd*
4921 argument. This should be an absolute path. A relative *path* will be resolved
4922 against this argument.
4923
4924 Use *show_cmd* to override the default window style. Whether this has any
4925 effect will depend on the application being launched. Values are integers as
4926 supported by the Win32 :c:func:`!ShellExecute` function.
4927
4928 :func:`startfile` returns as soon as the associated application is launched.
4929 There is no option to wait for the application to close, and no way to retrieve
4930 the application's exit status. The *path* parameter is relative to the current
4931 directory or *cwd*. If you want to use an absolute path, make sure the first
4932 character is not a slash (``'/'``) Use :mod:`pathlib` or the
4933 :func:`os.path.normpath` function to ensure that paths are properly encoded for
4934 Win32.
4935
4936 To reduce interpreter startup overhead, the Win32 :c:func:`!ShellExecute`
4937 function is not resolved until this function is first called. If the function
4938 cannot be resolved, :exc:`NotImplementedError` will be raised.
4939
4940 .. audit-event:: os.startfile path,operation os.startfile
4941
4942 .. audit-event:: os.startfile/2 path,operation,arguments,cwd,show_cmd os.startfile
4943
4944 .. availability:: Windows.
4945
4946 .. versionchanged:: 3.10
4947 Added the *arguments*, *cwd* and *show_cmd* arguments, and the
4948 ``os.startfile/2`` audit event.
4949
4950
4951 .. function:: system(command)
4952
4953 Execute the command (a string) in a subshell. This is implemented by calling
4954 the Standard C function :c:func:`system`, and has the same limitations.
4955 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of
4956 the executed command. If *command* generates any output, it will be sent to
4957 the interpreter standard output stream. The C standard does not
4958 specify the meaning of the return value of the C function, so the return
4959 value of the Python function is system-dependent.
4960
4961 On Unix, the return value is the exit status of the process encoded in the
4962 format specified for :func:`wait`.
4963
4964 On Windows, the return value is that returned by the system shell after
4965 running *command*. The shell is given by the Windows environment variable
4966 :envvar:`COMSPEC`: it is usually :program:`cmd.exe`, which returns the exit
4967 status of the command run; on systems using a non-native shell, consult your
4968 shell documentation.
4969
4970 The :mod:`subprocess` module provides more powerful facilities for spawning
4971 new processes and retrieving their results; using that module is preferable
4972 to using this function. See the :ref:`subprocess-replacements` section in
4973 the :mod:`subprocess` documentation for some helpful recipes.
4974
4975 On Unix, :func:`waitstatus_to_exitcode` can be used to convert the result
4976 (exit status) into an exit code. On Windows, the result is directly the exit
4977 code.
4978
4979 .. audit-event:: os.system command os.system
4980
4981 .. availability:: Unix, Windows, not WASI, not Android, not iOS.
4982
4983
4984 .. function:: times()
4985
4986 Returns the current global process times.
4987 The return value is an object with five attributes:
4988
4989 * :attr:`!user` - user time
4990 * :attr:`!system` - system time
4991 * :attr:`!children_user` - user time of all child processes
4992 * :attr:`!children_system` - system time of all child processes
4993 * :attr:`!elapsed` - elapsed real time since a fixed point in the past
4994
4995 For backwards compatibility, this object also behaves like a five-tuple
4996 containing :attr:`!user`, :attr:`!system`, :attr:`!children_user`,
4997 :attr:`!children_system`, and :attr:`!elapsed` in that order.
4998
4999 See the Unix manual page
5000 :manpage:`times(2)` and `times(3) <https://man.freebsd.org/cgi/man.cgi?time(3)>`_ manual page on Unix or `the GetProcessTimes MSDN
5001 <https://docs.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes>`_
5002 on Windows. On Windows, only :attr:`!user` and :attr:`!system` are known; the other attributes are zero.
5003
5004 .. availability:: Unix, Windows.
5005
5006 .. versionchanged:: 3.3
5007 Return type changed from a tuple to a tuple-like object
5008 with named attributes.
5009
5010
5011 .. function:: wait()
5012
5013 Wait for completion of a child process, and return a tuple containing its pid
5014 and exit status indication: a 16-bit number, whose low byte is the signal number
5015 that killed the process, and whose high byte is the exit status (if the signal
5016 number is zero); the high bit of the low byte is set if a core file was
5017 produced.
5018
5019 If there are no children that could be waited for, :exc:`ChildProcessError`
5020 is raised.
5021
5022 :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
5023 exit code.
5024
5025 .. availability:: Unix, not WASI, not Android, not iOS.
5026
5027 .. seealso::
5028
5029 The other :func:`!wait*` functions documented below can be used to wait for the
5030 completion of a specific child process and have more options.
5031 :func:`waitpid` is the only one also available on Windows.
5032
5033
5034 .. function:: waitid(idtype, id, options, /)
5035
5036 Wait for the completion of a child process.
5037
5038 *idtype* can be :data:`P_PID`, :data:`P_PGID`, :data:`P_ALL`, or (on Linux) :data:`P_PIDFD`.
5039 The interpretation of *id* depends on it; see their individual descriptions.
5040
5041 *options* is an OR combination of flags. At least one of :data:`WEXITED`,
5042 :data:`WSTOPPED` or :data:`WCONTINUED` is required;
5043 :data:`WNOHANG` and :data:`WNOWAIT` are additional optional flags.
5044
5045 The return value is an object representing the data contained in the
5046 :c:type:`siginfo_t` structure with the following attributes:
5047
5048 * :attr:`!si_pid` (process ID)
5049 * :attr:`!si_uid` (real user ID of the child)
5050 * :attr:`!si_signo` (always :const:`~signal.SIGCHLD`)
5051 * :attr:`!si_status` (the exit status or signal number, depending on :attr:`!si_code`)
5052 * :attr:`!si_code` (see :data:`CLD_EXITED` for possible values)
5053
5054 If :data:`WNOHANG` is specified and there are no matching children in the
5055 requested state, ``None`` is returned.
5056 Otherwise, if there are no matching children
5057 that could be waited for, :exc:`ChildProcessError` is raised.
5058
5059 .. availability:: Unix, not WASI, not Android, not iOS.
5060
5061 .. versionadded:: 3.3
5062
5063 .. versionchanged:: 3.13
5064 This function is now available on macOS as well.
5065
5066
5067 .. function:: waitpid(pid, options, /)
5068
5069 The details of this function differ on Unix and Windows.
5070
5071 On Unix: Wait for completion of a child process given by process id *pid*, and
5072 return a tuple containing its process id and exit status indication (encoded as
5073 for :func:`wait`). The semantics of the call are affected by the value of the
5074 integer *options*, which should be ``0`` for normal operation.
5075
5076 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
5077 that specific process. If *pid* is ``0``, the request is for the status of any
5078 child in the process group of the current process. If *pid* is ``-1``, the
5079 request pertains to any child of the current process. If *pid* is less than
5080 ``-1``, status is requested for any process in the process group ``-pid`` (the
5081 absolute value of *pid*).
5082
5083 *options* is an OR combination of flags. If it contains :data:`WNOHANG` and
5084 there are no matching children in the requested state, ``(0, 0)`` is
5085 returned. Otherwise, if there are no matching children that could be waited
5086 for, :exc:`ChildProcessError` is raised. Other options that can be used are
5087 :data:`WUNTRACED` and :data:`WCONTINUED`.
5088
5089 On Windows: Wait for completion of a process given by process handle *pid*, and
5090 return a tuple containing *pid*, and its exit status shifted left by 8 bits
5091 (shifting makes cross-platform use of the function easier). A *pid* less than or
5092 equal to ``0`` has no special meaning on Windows, and raises an exception. The
5093 value of integer *options* has no effect. *pid* can refer to any process whose
5094 id is known, not necessarily a child process. The :func:`spawn\* <spawnl>`
5095 functions called with :const:`P_NOWAIT` return suitable process handles.
5096
5097 :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
5098 exit code.
5099
5100 .. availability:: Unix, Windows, not WASI, not Android, not iOS.
5101
5102 .. versionchanged:: 3.5
5103 If the system call is interrupted and the signal handler does not raise an
5104 exception, the function now retries the system call instead of raising an
5105 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
5106
5107
5108 .. function:: wait3(options)
5109
5110 Similar to :func:`waitpid`, except no process id argument is given and a
5111 3-element tuple containing the child's process id, exit status indication,
5112 and resource usage information is returned. Refer to
5113 :func:`resource.getrusage` for details on resource usage information. The
5114 *options* argument is the same as that provided to :func:`waitpid` and
5115 :func:`wait4`.
5116
5117 :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
5118 exitcode.
5119
5120 .. availability:: Unix, not WASI, not Android, not iOS.
5121
5122
5123 .. function:: wait4(pid, options)
5124
5125 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
5126 process id, exit status indication, and resource usage information is
5127 returned. Refer to :func:`resource.getrusage` for details on resource usage
5128 information. The arguments to :func:`wait4` are the same as those provided
5129 to :func:`waitpid`.
5130
5131 :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
5132 exitcode.
5133
5134 .. availability:: Unix, not WASI, not Android, not iOS.
5135
5136
5137 .. data:: P_PID
5138 P_PGID
5139 P_ALL
5140 P_PIDFD
5141
5142 These are the possible values for *idtype* in :func:`waitid`. They affect
5143 how *id* is interpreted:
5144
5145 * :data:`!P_PID` - wait for the child whose PID is *id*.
5146 * :data:`!P_PGID` - wait for any child whose progress group ID is *id*.
5147 * :data:`!P_ALL` - wait for any child; *id* is ignored.
5148 * :data:`!P_PIDFD` - wait for the child identified by the file descriptor
5149 *id* (a process file descriptor created with :func:`pidfd_open`).
5150
5151 .. availability:: Unix, not WASI, not Android, not iOS.
5152
5153 .. note:: :data:`!P_PIDFD` is only available on Linux >= 5.4.
5154
5155 .. versionadded:: 3.3
5156 .. versionadded:: 3.9
5157 The :data:`!P_PIDFD` constant.
5158
5159
5160 .. data:: WCONTINUED
5161
5162 This *options* flag for :func:`waitpid`, :func:`wait3`, :func:`wait4`, and
5163 :func:`waitid` causes child processes to be reported if they have been
5164 continued from a job control stop since they were last reported.
5165
5166 .. availability:: Unix, not WASI, not Android, not iOS.
5167
5168
5169 .. data:: WEXITED
5170
5171 This *options* flag for :func:`waitid` causes child processes that have terminated to
5172 be reported.
5173
5174 The other ``wait*`` functions always report children that have terminated,
5175 so this option is not available for them.
5176
5177 .. availability:: Unix, not WASI, not Android, not iOS.
5178
5179 .. versionadded:: 3.3
5180
5181
5182 .. data:: WSTOPPED
5183
5184 This *options* flag for :func:`waitid` causes child processes that have been stopped
5185 by the delivery of a signal to be reported.
5186
5187 This option is not available for the other ``wait*`` functions.
5188
5189 .. availability:: Unix, not WASI, not Android, not iOS.
5190
5191 .. versionadded:: 3.3
5192
5193
5194 .. data:: WUNTRACED
5195
5196 This *options* flag for :func:`waitpid`, :func:`wait3`, and :func:`wait4` causes
5197 child processes to also be reported if they have been stopped but their
5198 current state has not been reported since they were stopped.
5199
5200 This option is not available for :func:`waitid`.
5201
5202 .. availability:: Unix, not WASI, not Android, not iOS.
5203
5204
5205 .. data:: WNOHANG
5206
5207 This *options* flag causes :func:`waitpid`, :func:`wait3`, :func:`wait4`, and
5208 :func:`waitid` to return right away if no child process status is available
5209 immediately.
5210
5211 .. availability:: Unix, not WASI, not Android, not iOS.
5212
5213
5214 .. data:: WNOWAIT
5215
5216 This *options* flag causes :func:`waitid` to leave the child in a waitable state, so that
5217 a later :func:`!wait*` call can be used to retrieve the child status information again.
5218
5219 This option is not available for the other ``wait*`` functions.
5220
5221 .. availability:: Unix, not WASI, not Android, not iOS.
5222
5223
5224 .. data:: CLD_EXITED
5225 CLD_KILLED
5226 CLD_DUMPED
5227 CLD_TRAPPED
5228 CLD_STOPPED
5229 CLD_CONTINUED
5230
5231 These are the possible values for :attr:`!si_code` in the result returned by
5232 :func:`waitid`.
5233
5234 .. availability:: Unix, not WASI, not Android, not iOS.
5235
5236 .. versionadded:: 3.3
5237
5238 .. versionchanged:: 3.9
5239 Added :data:`CLD_KILLED` and :data:`CLD_STOPPED` values.
5240
5241
5242 .. function:: waitstatus_to_exitcode(status)
5243
5244 Convert a wait status to an exit code.
5245
5246 On Unix:
5247
5248 * If the process exited normally (if ``WIFEXITED(status)`` is true),
5249 return the process exit status (return ``WEXITSTATUS(status)``):
5250 result greater than or equal to 0.
5251 * If the process was terminated by a signal (if ``WIFSIGNALED(status)`` is
5252 true), return ``-signum`` where *signum* is the number of the signal that
5253 caused the process to terminate (return ``-WTERMSIG(status)``):
5254 result less than 0.
5255 * Otherwise, raise a :exc:`ValueError`.
5256
5257 On Windows, return *status* shifted right by 8 bits.
5258
5259 On Unix, if the process is being traced or if :func:`waitpid` was called
5260 with :data:`WUNTRACED` option, the caller must first check if
5261 ``WIFSTOPPED(status)`` is true. This function must not be called if
5262 ``WIFSTOPPED(status)`` is true.
5263
5264 .. seealso::
5265
5266 :func:`WIFEXITED`, :func:`WEXITSTATUS`, :func:`WIFSIGNALED`,
5267 :func:`WTERMSIG`, :func:`WIFSTOPPED`, :func:`WSTOPSIG` functions.
5268
5269 .. availability:: Unix, Windows, not WASI, not Android, not iOS.
5270
5271 .. versionadded:: 3.9
5272
5273
5274 The following functions take a process status code as returned by
5275 :func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
5276 used to determine the disposition of a process.
5277
5278 .. function:: WCOREDUMP(status, /)
5279
5280 Return ``True`` if a core dump was generated for the process, otherwise
5281 return ``False``.
5282
5283 This function should be employed only if :func:`WIFSIGNALED` is true.
5284
5285 .. availability:: Unix, not WASI, not Android, not iOS.
5286
5287
5288 .. function:: WIFCONTINUED(status)
5289
5290 Return ``True`` if a stopped child has been resumed by delivery of
5291 :const:`~signal.SIGCONT` (if the process has been continued from a job
5292 control stop), otherwise return ``False``.
5293
5294 See :data:`WCONTINUED` option.
5295
5296 .. availability:: Unix, not WASI, not Android, not iOS.
5297
5298
5299 .. function:: WIFSTOPPED(status)
5300
5301 Return ``True`` if the process was stopped by delivery of a signal,
5302 otherwise return ``False``.
5303
5304 :func:`WIFSTOPPED` only returns ``True`` if the :func:`waitpid` call was
5305 done using :data:`WUNTRACED` option or when the process is being traced (see
5306 :manpage:`ptrace(2)`).
5307
5308 .. availability:: Unix, not WASI, not Android, not iOS.
5309
5310 .. function:: WIFSIGNALED(status)
5311
5312 Return ``True`` if the process was terminated by a signal, otherwise return
5313 ``False``.
5314
5315 .. availability:: Unix, not WASI, not Android, not iOS.
5316
5317
5318 .. function:: WIFEXITED(status)
5319
5320 Return ``True`` if the process exited terminated normally, that is,
5321 by calling ``exit()`` or ``_exit()``, or by returning from ``main()``;
5322 otherwise return ``False``.
5323
5324 .. availability:: Unix, not WASI, not Android, not iOS.
5325
5326
5327 .. function:: WEXITSTATUS(status)
5328
5329 Return the process exit status.
5330
5331 This function should be employed only if :func:`WIFEXITED` is true.
5332
5333 .. availability:: Unix, not WASI, not Android, not iOS.
5334
5335
5336 .. function:: WSTOPSIG(status)
5337
5338 Return the signal which caused the process to stop.
5339
5340 This function should be employed only if :func:`WIFSTOPPED` is true.
5341
5342 .. availability:: Unix, not WASI, not Android, not iOS.
5343
5344
5345 .. function:: WTERMSIG(status)
5346
5347 Return the number of the signal that caused the process to terminate.
5348
5349 This function should be employed only if :func:`WIFSIGNALED` is true.
5350
5351 .. availability:: Unix, not WASI, not Android, not iOS.
5352
5353
5354 Interface to the scheduler
5355 --------------------------
5356
5357 These functions control how a process is allocated CPU time by the operating
5358 system. They are only available on some Unix platforms. For more detailed
5359 information, consult your Unix manpages.
5360
5361 .. versionadded:: 3.3
5362
5363 The following scheduling policies are exposed if they are supported by the
5364 operating system.
5365
5366 .. _os-scheduling-policy:
5367
5368 .. data:: SCHED_OTHER
5369
5370 The default scheduling policy.
5371
5372 .. data:: SCHED_BATCH
5373
5374 Scheduling policy for CPU-intensive processes that tries to preserve
5375 interactivity on the rest of the computer.
5376
5377 .. data:: SCHED_IDLE
5378
5379 Scheduling policy for extremely low priority background tasks.
5380
5381 .. data:: SCHED_SPORADIC
5382
5383 Scheduling policy for sporadic server programs.
5384
5385 .. data:: SCHED_FIFO
5386
5387 A First In First Out scheduling policy.
5388
5389 .. data:: SCHED_RR
5390
5391 A round-robin scheduling policy.
5392
5393 .. data:: SCHED_RESET_ON_FORK
5394
5395 This flag can be OR'ed with any other scheduling policy. When a process with
5396 this flag set forks, its child's scheduling policy and priority are reset to
5397 the default.
5398
5399
5400 .. class:: sched_param(sched_priority)
5401
5402 This class represents tunable scheduling parameters used in
5403 :func:`sched_setparam`, :func:`sched_setscheduler`, and
5404 :func:`sched_getparam`. It is immutable.
5405
5406 At the moment, there is only one possible parameter:
5407
5408 .. attribute:: sched_priority
5409
5410 The scheduling priority for a scheduling policy.
5411
5412
5413 .. function:: sched_get_priority_min(policy)
5414
5415 Get the minimum priority value for *policy*. *policy* is one of the
5416 scheduling policy constants above.
5417
5418
5419 .. function:: sched_get_priority_max(policy)
5420
5421 Get the maximum priority value for *policy*. *policy* is one of the
5422 scheduling policy constants above.
5423
5424
5425 .. function:: sched_setscheduler(pid, policy, param, /)
5426
5427 Set the scheduling policy for the process with PID *pid*. A *pid* of 0 means
5428 the calling process. *policy* is one of the scheduling policy constants
5429 above. *param* is a :class:`sched_param` instance.
5430
5431
5432 .. function:: sched_getscheduler(pid, /)
5433
5434 Return the scheduling policy for the process with PID *pid*. A *pid* of 0
5435 means the calling process. The result is one of the scheduling policy
5436 constants above.
5437
5438
5439 .. function:: sched_setparam(pid, param, /)
5440
5441 Set the scheduling parameters for the process with PID *pid*. A *pid* of 0 means
5442 the calling process. *param* is a :class:`sched_param` instance.
5443
5444
5445 .. function:: sched_getparam(pid, /)
5446
5447 Return the scheduling parameters as a :class:`sched_param` instance for the
5448 process with PID *pid*. A *pid* of 0 means the calling process.
5449
5450
5451 .. function:: sched_rr_get_interval(pid, /)
5452
5453 Return the round-robin quantum in seconds for the process with PID *pid*. A
5454 *pid* of 0 means the calling process.
5455
5456
5457 .. function:: sched_yield()
5458
5459 Voluntarily relinquish the CPU. See :manpage:`sched_yield(2)` for details.
5460
5461
5462 .. function:: sched_setaffinity(pid, mask, /)
5463
5464 Restrict the process with PID *pid* (or the current process if zero) to a
5465 set of CPUs. *mask* is an iterable of integers representing the set of
5466 CPUs to which the process should be restricted.
5467
5468
5469 .. function:: sched_getaffinity(pid, /)
5470
5471 Return the set of CPUs the process with PID *pid* is restricted to.
5472
5473 If *pid* is zero, return the set of CPUs the calling thread of the current
5474 process is restricted to.
5475
5476 See also the :func:`process_cpu_count` function.
5477
5478
5479 .. _os-path:
5480
5481 Miscellaneous System Information
5482 --------------------------------
5483
5484
5485 .. function:: confstr(name, /)
5486
5487 Return string-valued system configuration values. *name* specifies the
5488 configuration value to retrieve; it may be a string which is the name of a
5489 defined system value; these names are specified in a number of standards (POSIX,
5490 Unix 95, Unix 98, and others). Some platforms define additional names as well.
5491 The names known to the host operating system are given as the keys of the
5492 ``confstr_names`` dictionary. For configuration variables not included in that
5493 mapping, passing an integer for *name* is also accepted.
5494
5495 If the configuration value specified by *name* isn't defined, ``None`` is
5496 returned.
5497
5498 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
5499 specific value for *name* is not supported by the host system, even if it is
5500 included in ``confstr_names``, an :exc:`OSError` is raised with
5501 :const:`errno.EINVAL` for the error number.
5502
5503 .. availability:: Unix.
5504
5505
5506 .. data:: confstr_names
5507
5508 Dictionary mapping names accepted by :func:`confstr` to the integer values
5509 defined for those names by the host operating system. This can be used to
5510 determine the set of names known to the system.
5511
5512 .. availability:: Unix.
5513
5514
5515 .. function:: cpu_count()
5516
5517 Return the number of logical CPUs in the **system**. Returns ``None`` if
5518 undetermined.
5519
5520 The :func:`process_cpu_count` function can be used to get the number of
5521 logical CPUs usable by the calling thread of the **current process**.
5522
5523 .. versionadded:: 3.4
5524
5525 .. versionchanged:: 3.13
5526 If :option:`-X cpu_count <-X>` is given or :envvar:`PYTHON_CPU_COUNT` is set,
5527 :func:`cpu_count` returns the override value *n*.
5528
5529
5530 .. function:: getloadavg()
5531
5532 Return the number of processes in the system run queue averaged over the last
5533 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
5534 unobtainable.
5535
5536 .. availability:: Unix.
5537
5538
5539 .. function:: process_cpu_count()
5540
5541 Get the number of logical CPUs usable by the calling thread of the **current
5542 process**. Returns ``None`` if undetermined. It can be less than
5543 :func:`cpu_count` depending on the CPU affinity.
5544
5545 The :func:`cpu_count` function can be used to get the number of logical CPUs
5546 in the **system**.
5547
5548 If :option:`-X cpu_count <-X>` is given or :envvar:`PYTHON_CPU_COUNT` is set,
5549 :func:`process_cpu_count` returns the override value *n*.
5550
5551 See also the :func:`sched_getaffinity` function.
5552
5553 .. versionadded:: 3.13
5554
5555
5556 .. function:: sysconf(name, /)
5557
5558 Return integer-valued system configuration values. If the configuration value
5559 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
5560 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
5561 provides information on the known names is given by ``sysconf_names``.
5562
5563 .. availability:: Unix.
5564
5565
5566 .. data:: sysconf_names
5567
5568 Dictionary mapping names accepted by :func:`sysconf` to the integer values
5569 defined for those names by the host operating system. This can be used to
5570 determine the set of names known to the system.
5571
5572 .. availability:: Unix.
5573
5574 .. versionchanged:: 3.11
5575 Add ``'SC_MINSIGSTKSZ'`` name.
5576
5577 The following data values are used to support path manipulation operations. These
5578 are defined for all platforms.
5579
5580 Higher-level operations on pathnames are defined in the :mod:`os.path` module.
5581
5582
5583 .. index:: single: . (dot); in pathnames
5584 .. data:: curdir
5585
5586 The constant string used by the operating system to refer to the current
5587 directory. This is ``'.'`` for Windows and POSIX. Also available via
5588 :mod:`os.path`.
5589
5590
5591 .. index:: single: ..; in pathnames
5592 .. data:: pardir
5593
5594 The constant string used by the operating system to refer to the parent
5595 directory. This is ``'..'`` for Windows and POSIX. Also available via
5596 :mod:`os.path`.
5597
5598
5599 .. index:: single: / (slash); in pathnames
5600 .. index:: single: \ (backslash); in pathnames (Windows)
5601 .. data:: sep
5602
5603 The character used by the operating system to separate pathname components.
5604 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
5605 is not sufficient to be able to parse or concatenate pathnames --- use
5606 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
5607 useful. Also available via :mod:`os.path`.
5608
5609
5610 .. index:: single: / (slash); in pathnames
5611 .. data:: altsep
5612
5613 An alternative character used by the operating system to separate pathname
5614 components, or ``None`` if only one separator character exists. This is set to
5615 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
5616 :mod:`os.path`.
5617
5618
5619 .. index:: single: . (dot); in pathnames
5620 .. data:: extsep
5621
5622 The character which separates the base filename from the extension; for example,
5623 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
5624
5625
5626 .. index:: single: : (colon); path separator (POSIX)
5627 single: ; (semicolon)
5628 .. data:: pathsep
5629
5630 The character conventionally used by the operating system to separate search
5631 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
5632 Windows. Also available via :mod:`os.path`.
5633
5634
5635 .. data:: defpath
5636
5637 The default search path used by :func:`exec\*p\* <execl>` and
5638 :func:`spawn\*p\* <spawnl>` if the environment doesn't have a ``'PATH'``
5639 key. Also available via :mod:`os.path`.
5640
5641
5642 .. data:: linesep
5643
5644 The string used to separate (or, rather, terminate) lines on the current
5645 platform. This may be a single character, such as ``'\n'`` for POSIX, or
5646 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
5647 *os.linesep* as a line terminator when writing files opened in text mode (the
5648 default); use a single ``'\n'`` instead, on all platforms.
5649
5650
5651 .. data:: devnull
5652
5653 The file path of the null device. For example: ``'/dev/null'`` for
5654 POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`.
5655
5656 .. data:: RTLD_LAZY
5657 RTLD_NOW
5658 RTLD_GLOBAL
5659 RTLD_LOCAL
5660 RTLD_NODELETE
5661 RTLD_NOLOAD
5662 RTLD_DEEPBIND
5663
5664 Flags for use with the :func:`~sys.setdlopenflags` and
5665 :func:`~sys.getdlopenflags` functions. See the Unix manual page
5666 :manpage:`dlopen(3)` for what the different flags mean.
5667
5668 .. versionadded:: 3.3
5669
5670
5671 Random numbers
5672 --------------
5673
5674
5675 .. function:: getrandom(size, flags=0)
5676
5677 Get up to *size* random bytes. The function can return less bytes than
5678 requested.
5679
5680 These bytes can be used to seed user-space random number generators or for
5681 cryptographic purposes.
5682
5683 ``getrandom()`` relies on entropy gathered from device drivers and other
5684 sources of environmental noise. Unnecessarily reading large quantities of
5685 data will have a negative impact on other users of the ``/dev/random`` and
5686 ``/dev/urandom`` devices.
5687
5688 The flags argument is a bit mask that can contain zero or more of the
5689 following values ORed together: :py:const:`os.GRND_RANDOM` and
5690 :py:data:`GRND_NONBLOCK`.
5691
5692 See also the `Linux getrandom() manual page
5693 <https://man7.org/linux/man-pages/man2/getrandom.2.html>`_.
5694
5695 .. availability:: Linux >= 3.17.
5696
5697 .. versionadded:: 3.6
5698
5699 .. function:: urandom(size, /)
5700
5701 Return a bytestring of *size* random bytes suitable for cryptographic use.
5702
5703 This function returns random bytes from an OS-specific randomness source. The
5704 returned data should be unpredictable enough for cryptographic applications,
5705 though its exact quality depends on the OS implementation.
5706
5707 On Linux, if the ``getrandom()`` syscall is available, it is used in
5708 blocking mode: block until the system urandom entropy pool is initialized
5709 (128 bits of entropy are collected by the kernel). See the :pep:`524` for
5710 the rationale. On Linux, the :func:`getrandom` function can be used to get
5711 random bytes in non-blocking mode (using the :data:`GRND_NONBLOCK` flag) or
5712 to poll until the system urandom entropy pool is initialized.
5713
5714 On a Unix-like system, random bytes are read from the ``/dev/urandom``
5715 device. If the ``/dev/urandom`` device is not available or not readable, the
5716 :exc:`NotImplementedError` exception is raised.
5717
5718 On Windows, it will use ``BCryptGenRandom()``.
5719
5720 .. seealso::
5721 The :mod:`secrets` module provides higher level functions. For an
5722 easy-to-use interface to the random number generator provided by your
5723 platform, please see :class:`random.SystemRandom`.
5724
5725 .. versionchanged:: 3.5
5726 On Linux 3.17 and newer, the ``getrandom()`` syscall is now used
5727 when available. On OpenBSD 5.6 and newer, the C ``getentropy()``
5728 function is now used. These functions avoid the usage of an internal file
5729 descriptor.
5730
5731 .. versionchanged:: 3.5.2
5732 On Linux, if the ``getrandom()`` syscall blocks (the urandom entropy pool
5733 is not initialized yet), fall back on reading ``/dev/urandom``.
5734
5735 .. versionchanged:: 3.6
5736 On Linux, ``getrandom()`` is now used in blocking mode to increase the
5737 security.
5738
5739 .. versionchanged:: 3.11
5740 On Windows, ``BCryptGenRandom()`` is used instead of ``CryptGenRandom()``
5741 which is deprecated.
5742
5743 .. data:: GRND_NONBLOCK
5744
5745 By default, when reading from ``/dev/random``, :func:`getrandom` blocks if
5746 no random bytes are available, and when reading from ``/dev/urandom``, it blocks
5747 if the entropy pool has not yet been initialized.
5748
5749 If the :py:data:`GRND_NONBLOCK` flag is set, then :func:`getrandom` does not
5750 block in these cases, but instead immediately raises :exc:`BlockingIOError`.
5751
5752 .. versionadded:: 3.6
5753
5754 .. data:: GRND_RANDOM
5755
5756 If this bit is set, then random bytes are drawn from the
5757 ``/dev/random`` pool instead of the ``/dev/urandom`` pool.
5758
5759 .. versionadded:: 3.6