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