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   This function can also support :ref:`paths relative to directory descriptors
2139   <dir_fd>`.
2140
2141   It is also possible to create temporary directories; see the
2142   :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
2143
2144   .. audit-event:: os.mkdir path,mode,dir_fd os.mkdir
2145
2146   .. versionadded:: 3.3
2147      The *dir_fd* argument.
2148
2149   .. versionchanged:: 3.6
2150      Accepts a :term:`path-like object`.
2151
2152
2153.. function:: makedirs(name, mode=0o777, exist_ok=False)
2154
2155   .. index::
2156      single: directory; creating
2157      single: UNC paths; and os.makedirs()
2158
2159   Recursive directory creation function.  Like :func:`mkdir`, but makes all
2160   intermediate-level directories needed to contain the leaf directory.
2161
2162   The *mode* parameter is passed to :func:`mkdir` for creating the leaf
2163   directory; see :ref:`the mkdir() description <mkdir_modebits>` for how it
2164   is interpreted.  To set the file permission bits of any newly created parent
2165   directories you can set the umask before invoking :func:`makedirs`.  The
2166   file permission bits of existing parent directories are not changed.
2167
2168   If *exist_ok* is ``False`` (the default), a :exc:`FileExistsError` is
2169   raised if the target directory already exists.
2170
2171   .. note::
2172
2173      :func:`makedirs` will become confused if the path elements to create
2174      include :data:`pardir` (eg. ".." on UNIX systems).
2175
2176   This function handles UNC paths correctly.
2177
2178   .. audit-event:: os.mkdir path,mode,dir_fd os.makedirs
2179
2180   .. versionadded:: 3.2
2181      The *exist_ok* parameter.
2182
2183   .. versionchanged:: 3.4.1
2184
2185      Before Python 3.4.1, if *exist_ok* was ``True`` and the directory existed,
2186      :func:`makedirs` would still raise an error if *mode* did not match the
2187      mode of the existing directory. Since this behavior was impossible to
2188      implement safely, it was removed in Python 3.4.1. See :issue:`21082`.
2189
2190   .. versionchanged:: 3.6
2191      Accepts a :term:`path-like object`.
2192
2193   .. versionchanged:: 3.7
2194      The *mode* argument no longer affects the file permission bits of
2195      newly created intermediate-level directories.
2196
2197
2198.. function:: mkfifo(path, mode=0o666, *, dir_fd=None)
2199
2200   Create a FIFO (a named pipe) named *path* with numeric mode *mode*.
2201   The current umask value is first masked out from the mode.
2202
2203   This function can also support :ref:`paths relative to directory descriptors
2204   <dir_fd>`.
2205
2206   FIFOs are pipes that can be accessed like regular files.  FIFOs exist until they
2207   are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
2208   rendezvous between "client" and "server" type processes: the server opens the
2209   FIFO for reading, and the client opens it for writing.  Note that :func:`mkfifo`
2210   doesn't open the FIFO --- it just creates the rendezvous point.
2211
2212   .. availability:: Unix, not Emscripten, not WASI.
2213
2214   .. versionadded:: 3.3
2215      The *dir_fd* argument.
2216
2217   .. versionchanged:: 3.6
2218      Accepts a :term:`path-like object`.
2219
2220
2221.. function:: mknod(path, mode=0o600, device=0, *, dir_fd=None)
2222
2223   Create a filesystem node (file, device special file or named pipe) named
2224   *path*. *mode* specifies both the permissions to use and the type of node
2225   to be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
2226   ``stat.S_IFCHR``, ``stat.S_IFBLK``, and ``stat.S_IFIFO`` (those constants are
2227   available in :mod:`stat`).  For ``stat.S_IFCHR`` and ``stat.S_IFBLK``,
2228   *device* defines the newly created device special file (probably using
2229   :func:`os.makedev`), otherwise it is ignored.
2230
2231   This function can also support :ref:`paths relative to directory descriptors
2232   <dir_fd>`.
2233
2234   .. availability:: Unix, not Emscripten, not WASI.
2235
2236   .. versionadded:: 3.3
2237      The *dir_fd* argument.
2238
2239   .. versionchanged:: 3.6
2240      Accepts a :term:`path-like object`.
2241
2242
2243.. function:: major(device, /)
2244
2245   Extract the device major number from a raw device number (usually the
2246   :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).
2247
2248
2249.. function:: minor(device, /)
2250
2251   Extract the device minor number from a raw device number (usually the
2252   :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).
2253
2254
2255.. function:: makedev(major, minor, /)
2256
2257   Compose a raw device number from the major and minor device numbers.
2258
2259
2260.. function:: pathconf(path, name)
2261
2262   Return system configuration information relevant to a named file. *name*
2263   specifies the configuration value to retrieve; it may be a string which is the
2264   name of a defined system value; these names are specified in a number of
2265   standards (POSIX.1, Unix 95, Unix 98, and others).  Some platforms define
2266   additional names as well.  The names known to the host operating system are
2267   given in the ``pathconf_names`` dictionary.  For configuration variables not
2268   included in that mapping, passing an integer for *name* is also accepted.
2269
2270   If *name* is a string and is not known, :exc:`ValueError` is raised.  If a
2271   specific value for *name* is not supported by the host system, even if it is
2272   included in ``pathconf_names``, an :exc:`OSError` is raised with
2273   :const:`errno.EINVAL` for the error number.
2274
2275   This function can support :ref:`specifying a file descriptor
2276   <path_fd>`.
2277
2278   .. availability:: Unix.
2279
2280   .. versionchanged:: 3.6
2281      Accepts a :term:`path-like object`.
2282
2283
2284.. data:: pathconf_names
2285
2286   Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
2287   the integer values defined for those names by the host operating system.  This
2288   can be used to determine the set of names known to the system.
2289
2290   .. availability:: Unix.
2291
2292
2293.. function:: readlink(path, *, dir_fd=None)
2294
2295   Return a string representing the path to which the symbolic link points.  The
2296   result may be either an absolute or relative pathname; if it is relative, it
2297   may be converted to an absolute pathname using
2298   ``os.path.join(os.path.dirname(path), result)``.
2299
2300   If the *path* is a string object (directly or indirectly through a
2301   :class:`PathLike` interface), the result will also be a string object,
2302   and the call may raise a UnicodeDecodeError. If the *path* is a bytes
2303   object (direct or indirectly), the result will be a bytes object.
2304
2305   This function can also support :ref:`paths relative to directory descriptors
2306   <dir_fd>`.
2307
2308   When trying to resolve a path that may contain links, use
2309   :func:`~os.path.realpath` to properly handle recursion and platform
2310   differences.
2311
2312   .. availability:: Unix, Windows.
2313
2314   .. versionchanged:: 3.2
2315      Added support for Windows 6.0 (Vista) symbolic links.
2316
2317   .. versionadded:: 3.3
2318      The *dir_fd* argument.
2319
2320   .. versionchanged:: 3.6
2321      Accepts a :term:`path-like object` on Unix.
2322
2323   .. versionchanged:: 3.8
2324      Accepts a :term:`path-like object` and a bytes object on Windows.
2325
2326   .. versionchanged:: 3.8
2327      Added support for directory junctions, and changed to return the
2328      substitution path (which typically includes ``\\?\`` prefix) rather
2329      than the optional "print name" field that was previously returned.
2330
2331.. function:: remove(path, *, dir_fd=None)
2332
2333   Remove (delete) the file *path*.  If *path* is a directory, an
2334   :exc:`OSError` is raised.  Use :func:`rmdir` to remove directories.
2335   If the file does not exist, a :exc:`FileNotFoundError` is raised.
2336
2337   This function can support :ref:`paths relative to directory descriptors
2338   <dir_fd>`.
2339
2340   On Windows, attempting to remove a file that is in use causes an exception to
2341   be raised; on Unix, the directory entry is removed but the storage allocated
2342   to the file is not made available until the original file is no longer in use.
2343
2344   This function is semantically identical to :func:`unlink`.
2345
2346   .. audit-event:: os.remove path,dir_fd os.remove
2347
2348   .. versionadded:: 3.3
2349      The *dir_fd* argument.
2350
2351   .. versionchanged:: 3.6
2352      Accepts a :term:`path-like object`.
2353
2354
2355.. function:: removedirs(name)
2356
2357   .. index:: single: directory; deleting
2358
2359   Remove directories recursively.  Works like :func:`rmdir` except that, if the
2360   leaf directory is successfully removed, :func:`removedirs`  tries to
2361   successively remove every parent directory mentioned in  *path* until an error
2362   is raised (which is ignored, because it generally means that a parent directory
2363   is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
2364   the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
2365   they are empty. Raises :exc:`OSError` if the leaf directory could not be
2366   successfully removed.
2367
2368   .. audit-event:: os.remove path,dir_fd os.removedirs
2369
2370   .. versionchanged:: 3.6
2371      Accepts a :term:`path-like object`.
2372
2373
2374.. function:: rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
2375
2376   Rename the file or directory *src* to *dst*. If *dst* exists, the operation
2377   will fail with an :exc:`OSError` subclass in a number of cases:
2378
2379   On Windows, if *dst* exists a :exc:`FileExistsError` is always raised.
2380   The operation may fail if *src* and *dst* are on different filesystems. Use
2381   :func:`shutil.move` to support moves to a different filesystem.
2382
2383   On Unix, if *src* is a file and *dst* is a directory or vice-versa, an
2384   :exc:`IsADirectoryError` or a :exc:`NotADirectoryError` will be raised
2385   respectively.  If both are directories and *dst* is empty, *dst* will be
2386   silently replaced.  If *dst* is a non-empty directory, an :exc:`OSError`
2387   is raised. If both are files, *dst* will be replaced silently if the user
2388   has permission.  The operation may fail on some Unix flavors if *src* and
2389   *dst* are on different filesystems.  If successful, the renaming will be an
2390   atomic operation (this is a POSIX requirement).
2391
2392   This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
2393   supply :ref:`paths relative to directory descriptors <dir_fd>`.
2394
2395   If you want cross-platform overwriting of the destination, use :func:`replace`.
2396
2397   .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.rename
2398
2399   .. versionadded:: 3.3
2400      The *src_dir_fd* and *dst_dir_fd* arguments.
2401
2402   .. versionchanged:: 3.6
2403      Accepts a :term:`path-like object` for *src* and *dst*.
2404
2405
2406.. function:: renames(old, new)
2407
2408   Recursive directory or file renaming function. Works like :func:`rename`, except
2409   creation of any intermediate directories needed to make the new pathname good is
2410   attempted first. After the rename, directories corresponding to rightmost path
2411   segments of the old name will be pruned away using :func:`removedirs`.
2412
2413   .. note::
2414
2415      This function can fail with the new directory structure made if you lack
2416      permissions needed to remove the leaf directory or file.
2417
2418   .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.renames
2419
2420   .. versionchanged:: 3.6
2421      Accepts a :term:`path-like object` for *old* and *new*.
2422
2423
2424.. function:: replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
2425
2426   Rename the file or directory *src* to *dst*.  If *dst* is a non-empty directory,
2427   :exc:`OSError` will be raised.  If *dst* exists and is a file, it will
2428   be replaced silently if the user has permission.  The operation may fail
2429   if *src* and *dst* are on different filesystems.  If successful,
2430   the renaming will be an atomic operation (this is a POSIX requirement).
2431
2432   This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
2433   supply :ref:`paths relative to directory descriptors <dir_fd>`.
2434
2435   .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.replace
2436
2437   .. versionadded:: 3.3
2438
2439   .. versionchanged:: 3.6
2440      Accepts a :term:`path-like object` for *src* and *dst*.
2441
2442
2443.. function:: rmdir(path, *, dir_fd=None)
2444
2445   Remove (delete) the directory *path*.  If the directory does not exist or is
2446   not empty, a :exc:`FileNotFoundError` or an :exc:`OSError` is raised
2447   respectively.  In order to remove whole directory trees,
2448   :func:`shutil.rmtree` can be used.
2449
2450   This function can support :ref:`paths relative to directory descriptors
2451   <dir_fd>`.
2452
2453   .. audit-event:: os.rmdir path,dir_fd os.rmdir
2454
2455   .. versionadded:: 3.3
2456      The *dir_fd* parameter.
2457
2458   .. versionchanged:: 3.6
2459      Accepts a :term:`path-like object`.
2460
2461
2462.. function:: scandir(path='.')
2463
2464   Return an iterator of :class:`os.DirEntry` objects corresponding to the
2465   entries in the directory given by *path*. The entries are yielded in
2466   arbitrary order, and the special entries ``'.'`` and ``'..'`` are not
2467   included.  If a file is removed from or added to the directory after
2468   creating the iterator, whether an entry for that file be included is
2469   unspecified.
2470
2471   Using :func:`scandir` instead of :func:`listdir` can significantly
2472   increase the performance of code that also needs file type or file
2473   attribute information, because :class:`os.DirEntry` objects expose this
2474   information if the operating system provides it when scanning a directory.
2475   All :class:`os.DirEntry` methods may perform a system call, but
2476   :func:`~os.DirEntry.is_dir` and :func:`~os.DirEntry.is_file` usually only
2477   require a system call for symbolic links; :func:`os.DirEntry.stat`
2478   always requires a system call on Unix but only requires one for
2479   symbolic links on Windows.
2480
2481   *path* may be a :term:`path-like object`.  If *path* is of type ``bytes``
2482   (directly or indirectly through the :class:`PathLike` interface),
2483   the type of the :attr:`~os.DirEntry.name` and :attr:`~os.DirEntry.path`
2484   attributes of each :class:`os.DirEntry` will be ``bytes``; in all other
2485   circumstances, they will be of type ``str``.
2486
2487   This function can also support :ref:`specifying a file descriptor
2488   <path_fd>`; the file descriptor must refer to a directory.
2489
2490   .. audit-event:: os.scandir path os.scandir
2491
2492   The :func:`scandir` iterator supports the :term:`context manager` protocol
2493   and has the following method:
2494
2495   .. method:: scandir.close()
2496
2497      Close the iterator and free acquired resources.
2498
2499      This is called automatically when the iterator is exhausted or garbage
2500      collected, or when an error happens during iterating.  However it
2501      is advisable to call it explicitly or use the :keyword:`with`
2502      statement.
2503
2504      .. versionadded:: 3.6
2505
2506   The following example shows a simple use of :func:`scandir` to display all
2507   the files (excluding directories) in the given *path* that don't start with
2508   ``'.'``. The ``entry.is_file()`` call will generally not make an additional
2509   system call::
2510
2511      with os.scandir(path) as it:
2512          for entry in it:
2513              if not entry.name.startswith('.') and entry.is_file():
2514                  print(entry.name)
2515
2516   .. note::
2517
2518      On Unix-based systems, :func:`scandir` uses the system's
2519      `opendir() <https://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html>`_
2520      and
2521      `readdir() <https://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html>`_
2522      functions. On Windows, it uses the Win32
2523      `FindFirstFileW <https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx>`_
2524      and
2525      `FindNextFileW <https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx>`_
2526      functions.
2527
2528   .. versionadded:: 3.5
2529
2530   .. versionadded:: 3.6
2531      Added support for the :term:`context manager` protocol and the
2532      :func:`~scandir.close()` method.  If a :func:`scandir` iterator is neither
2533      exhausted nor explicitly closed a :exc:`ResourceWarning` will be emitted
2534      in its destructor.
2535
2536      The function accepts a :term:`path-like object`.
2537
2538   .. versionchanged:: 3.7
2539      Added support for :ref:`file descriptors <path_fd>` on Unix.
2540
2541
2542.. class:: DirEntry
2543
2544   Object yielded by :func:`scandir` to expose the file path and other file
2545   attributes of a directory entry.
2546
2547   :func:`scandir` will provide as much of this information as possible without
2548   making additional system calls. When a ``stat()`` or ``lstat()`` system call
2549   is made, the ``os.DirEntry`` object will cache the result.
2550
2551   ``os.DirEntry`` instances are not intended to be stored in long-lived data
2552   structures; if you know the file metadata has changed or if a long time has
2553   elapsed since calling :func:`scandir`, call ``os.stat(entry.path)`` to fetch
2554   up-to-date information.
2555
2556   Because the ``os.DirEntry`` methods can make operating system calls, they may
2557   also raise :exc:`OSError`. If you need very fine-grained
2558   control over errors, you can catch :exc:`OSError` when calling one of the
2559   ``os.DirEntry`` methods and handle as appropriate.
2560
2561   To be directly usable as a :term:`path-like object`, ``os.DirEntry``
2562   implements the :class:`PathLike` interface.
2563
2564   Attributes and methods on a ``os.DirEntry`` instance are as follows:
2565
2566   .. attribute:: name
2567
2568      The entry's base filename, relative to the :func:`scandir` *path*
2569      argument.
2570
2571      The :attr:`name` attribute will be ``bytes`` if the :func:`scandir`
2572      *path* argument is of type ``bytes`` and ``str`` otherwise.  Use
2573      :func:`~os.fsdecode` to decode byte filenames.
2574
2575   .. attribute:: path
2576
2577      The entry's full path name: equivalent to ``os.path.join(scandir_path,
2578      entry.name)`` where *scandir_path* is the :func:`scandir` *path*
2579      argument.  The path is only absolute if the :func:`scandir` *path*
2580      argument was absolute.  If the :func:`scandir` *path*
2581      argument was a :ref:`file descriptor <path_fd>`, the :attr:`path`
2582      attribute is the same as the :attr:`name` attribute.
2583
2584      The :attr:`path` attribute will be ``bytes`` if the :func:`scandir`
2585      *path* argument is of type ``bytes`` and ``str`` otherwise.  Use
2586      :func:`~os.fsdecode` to decode byte filenames.
2587
2588   .. method:: inode()
2589
2590      Return the inode number of the entry.
2591
2592      The result is cached on the ``os.DirEntry`` object. Use
2593      ``os.stat(entry.path, follow_symlinks=False).st_ino`` to fetch up-to-date
2594      information.
2595
2596      On the first, uncached call, a system call is required on Windows but
2597      not on Unix.
2598
2599   .. method:: is_dir(*, follow_symlinks=True)
2600
2601      Return ``True`` if this entry is a directory or a symbolic link pointing
2602      to a directory; return ``False`` if the entry is or points to any other
2603      kind of file, or if it doesn't exist anymore.
2604
2605      If *follow_symlinks* is ``False``, return ``True`` only if this entry
2606      is a directory (without following symlinks); return ``False`` if the
2607      entry is any other kind of file or if it doesn't exist anymore.
2608
2609      The result is cached on the ``os.DirEntry`` object, with a separate cache
2610      for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` along
2611      with :func:`stat.S_ISDIR` to fetch up-to-date information.
2612
2613      On the first, uncached call, no system call is required in most cases.
2614      Specifically, for non-symlinks, neither Windows or Unix require a system
2615      call, except on certain Unix file systems, such as network file systems,
2616      that return ``dirent.d_type == DT_UNKNOWN``. If the entry is a symlink,
2617      a system call will be required to follow the symlink unless
2618      *follow_symlinks* is ``False``.
2619
2620      This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2621      but :exc:`FileNotFoundError` is caught and not raised.
2622
2623   .. method:: is_file(*, follow_symlinks=True)
2624
2625      Return ``True`` if this entry is a file or a symbolic link pointing to a
2626      file; return ``False`` if the entry is or points to a directory or other
2627      non-file entry, or if it doesn't exist anymore.
2628
2629      If *follow_symlinks* is ``False``, return ``True`` only if this entry
2630      is a file (without following symlinks); return ``False`` if the entry is
2631      a directory or other non-file entry, or if it doesn't exist anymore.
2632
2633      The result is cached on the ``os.DirEntry`` object. Caching, system calls
2634      made, and exceptions raised are as per :func:`~os.DirEntry.is_dir`.
2635
2636   .. method:: is_symlink()
2637
2638      Return ``True`` if this entry is a symbolic link (even if broken);
2639      return ``False`` if the entry points to a directory or any kind of file,
2640      or if it doesn't exist anymore.
2641
2642      The result is cached on the ``os.DirEntry`` object. Call
2643      :func:`os.path.islink` to fetch up-to-date information.
2644
2645      On the first, uncached call, no system call is required in most cases.
2646      Specifically, neither Windows or Unix require a system call, except on
2647      certain Unix file systems, such as network file systems, that return
2648      ``dirent.d_type == DT_UNKNOWN``.
2649
2650      This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2651      but :exc:`FileNotFoundError` is caught and not raised.
2652
2653   .. method:: stat(*, follow_symlinks=True)
2654
2655      Return a :class:`stat_result` object for this entry. This method
2656      follows symbolic links by default; to stat a symbolic link add the
2657      ``follow_symlinks=False`` argument.
2658
2659      On Unix, this method always requires a system call. On Windows, it
2660      only requires a system call if *follow_symlinks* is ``True`` and the
2661      entry is a reparse point (for example, a symbolic link or directory
2662      junction).
2663
2664      On Windows, the ``st_ino``, ``st_dev`` and ``st_nlink`` attributes of the
2665      :class:`stat_result` are always set to zero. Call :func:`os.stat` to
2666      get these attributes.
2667
2668      The result is cached on the ``os.DirEntry`` object, with a separate cache
2669      for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` to
2670      fetch up-to-date information.
2671
2672   Note that there is a nice correspondence between several attributes
2673   and methods of ``os.DirEntry`` and of :class:`pathlib.Path`.  In
2674   particular, the ``name`` attribute has the same
2675   meaning, as do the ``is_dir()``, ``is_file()``, ``is_symlink()``
2676   and ``stat()`` methods.
2677
2678   .. versionadded:: 3.5
2679
2680   .. versionchanged:: 3.6
2681      Added support for the :class:`~os.PathLike` interface.  Added support
2682      for :class:`bytes` paths on Windows.
2683
2684
2685.. function:: stat(path, *, dir_fd=None, follow_symlinks=True)
2686
2687   Get the status of a file or a file descriptor. Perform the equivalent of a
2688   :c:func:`stat` system call on the given path. *path* may be specified as
2689   either a string or bytes -- directly or indirectly through the :class:`PathLike`
2690   interface -- or as an open file descriptor. Return a :class:`stat_result`
2691   object.
2692
2693   This function normally follows symlinks; to stat a symlink add the argument
2694   ``follow_symlinks=False``, or use :func:`lstat`.
2695
2696   This function can support :ref:`specifying a file descriptor <path_fd>` and
2697   :ref:`not following symlinks <follow_symlinks>`.
2698
2699   On Windows, passing ``follow_symlinks=False`` will disable following all
2700   name-surrogate reparse points, which includes symlinks and directory
2701   junctions. Other types of reparse points that do not resemble links or that
2702   the operating system is unable to follow will be opened directly. When
2703   following a chain of multiple links, this may result in the original link
2704   being returned instead of the non-link that prevented full traversal. To
2705   obtain stat results for the final path in this case, use the
2706   :func:`os.path.realpath` function to resolve the path name as far as
2707   possible and call :func:`lstat` on the result. This does not apply to
2708   dangling symlinks or junction points, which will raise the usual exceptions.
2709
2710   .. index:: pair: module; stat
2711
2712   Example::
2713
2714      >>> import os
2715      >>> statinfo = os.stat('somefile.txt')
2716      >>> statinfo
2717      os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
2718      st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
2719      st_mtime=1297230027, st_ctime=1297230027)
2720      >>> statinfo.st_size
2721      264
2722
2723   .. seealso::
2724
2725      :func:`fstat` and :func:`lstat` functions.
2726
2727   .. versionadded:: 3.3
2728      Added the *dir_fd* and *follow_symlinks* arguments, specifying a file
2729      descriptor instead of a path.
2730
2731   .. versionchanged:: 3.6
2732      Accepts a :term:`path-like object`.
2733
2734   .. versionchanged:: 3.8
2735      On Windows, all reparse points that can be resolved by the operating
2736      system are now followed, and passing ``follow_symlinks=False``
2737      disables following all name surrogate reparse points. If the operating
2738      system reaches a reparse point that it is not able to follow, *stat* now
2739      returns the information for the original path as if
2740      ``follow_symlinks=False`` had been specified instead of raising an error.
2741
2742
2743.. class:: stat_result
2744
2745   Object whose attributes correspond roughly to the members of the
2746   :c:type:`stat` structure. It is used for the result of :func:`os.stat`,
2747   :func:`os.fstat` and :func:`os.lstat`.
2748
2749   Attributes:
2750
2751   .. attribute:: st_mode
2752
2753      File mode: file type and file mode bits (permissions).
2754
2755   .. attribute:: st_ino
2756
2757      Platform dependent, but if non-zero, uniquely identifies the
2758      file for a given value of ``st_dev``. Typically:
2759
2760      * the inode number on Unix,
2761      * the `file index
2762        <https://msdn.microsoft.com/en-us/library/aa363788>`_ on
2763        Windows
2764
2765   .. attribute:: st_dev
2766
2767      Identifier of the device on which this file resides.
2768
2769   .. attribute:: st_nlink
2770
2771      Number of hard links.
2772
2773   .. attribute:: st_uid
2774
2775      User identifier of the file owner.
2776
2777   .. attribute:: st_gid
2778
2779      Group identifier of the file owner.
2780
2781   .. attribute:: st_size
2782
2783      Size of the file in bytes, if it is a regular file or a symbolic link.
2784      The size of a symbolic link is the length of the pathname it contains,
2785      without a terminating null byte.
2786
2787   Timestamps:
2788
2789   .. attribute:: st_atime
2790
2791      Time of most recent access expressed in seconds.
2792
2793   .. attribute:: st_mtime
2794
2795      Time of most recent content modification expressed in seconds.
2796
2797   .. attribute:: st_ctime
2798
2799      Platform dependent:
2800
2801      * the time of most recent metadata change on Unix,
2802      * the time of creation on Windows, expressed in seconds.
2803
2804   .. attribute:: st_atime_ns
2805
2806      Time of most recent access expressed in nanoseconds as an integer.
2807
2808   .. attribute:: st_mtime_ns
2809
2810      Time of most recent content modification expressed in nanoseconds as an
2811      integer.
2812
2813   .. attribute:: st_ctime_ns
2814
2815      Platform dependent:
2816
2817      * the time of most recent metadata change on Unix,
2818      * the time of creation on Windows, expressed in nanoseconds as an
2819        integer.
2820
2821   .. note::
2822
2823      The exact meaning and resolution of the :attr:`st_atime`,
2824      :attr:`st_mtime`, and :attr:`st_ctime` attributes depend on the operating
2825      system and the file system. For example, on Windows systems using the FAT
2826      or FAT32 file systems, :attr:`st_mtime` has 2-second resolution, and
2827      :attr:`st_atime` has only 1-day resolution.  See your operating system
2828      documentation for details.
2829
2830      Similarly, although :attr:`st_atime_ns`, :attr:`st_mtime_ns`,
2831      and :attr:`st_ctime_ns` are always expressed in nanoseconds, many
2832      systems do not provide nanosecond precision.  On systems that do
2833      provide nanosecond precision, the floating-point object used to
2834      store :attr:`st_atime`, :attr:`st_mtime`, and :attr:`st_ctime`
2835      cannot preserve all of it, and as such will be slightly inexact.
2836      If you need the exact timestamps you should always use
2837      :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and :attr:`st_ctime_ns`.
2838
2839   On some Unix systems (such as Linux), the following attributes may also be
2840   available:
2841
2842   .. attribute:: st_blocks
2843
2844      Number of 512-byte blocks allocated for file.
2845      This may be smaller than :attr:`st_size`/512 when the file has holes.
2846
2847   .. attribute:: st_blksize
2848
2849      "Preferred" blocksize for efficient file system I/O. Writing to a file in
2850      smaller chunks may cause an inefficient read-modify-rewrite.
2851
2852   .. attribute:: st_rdev
2853
2854      Type of device if an inode device.
2855
2856   .. attribute:: st_flags
2857
2858      User defined flags for file.
2859
2860   On other Unix systems (such as FreeBSD), the following attributes may be
2861   available (but may be only filled out if root tries to use them):
2862
2863   .. attribute:: st_gen
2864
2865      File generation number.
2866
2867   .. attribute:: st_birthtime
2868
2869      Time of file creation.
2870
2871   On Solaris and derivatives, the following attributes may also be
2872   available:
2873
2874   .. attribute:: st_fstype
2875
2876      String that uniquely identifies the type of the filesystem that
2877      contains the file.
2878
2879   On macOS systems, the following attributes may also be available:
2880
2881   .. attribute:: st_rsize
2882
2883      Real size of the file.
2884
2885   .. attribute:: st_creator
2886
2887      Creator of the file.
2888
2889   .. attribute:: st_type
2890
2891      File type.
2892
2893   On Windows systems, the following attributes are also available:
2894
2895   .. attribute:: st_file_attributes
2896
2897      Windows file attributes: ``dwFileAttributes`` member of the
2898      ``BY_HANDLE_FILE_INFORMATION`` structure returned by
2899      :c:func:`GetFileInformationByHandle`. See the ``FILE_ATTRIBUTE_*``
2900      constants in the :mod:`stat` module.
2901
2902   .. attribute:: st_reparse_tag
2903
2904      When :attr:`st_file_attributes` has the ``FILE_ATTRIBUTE_REPARSE_POINT``
2905      set, this field contains the tag identifying the type of reparse point.
2906      See the ``IO_REPARSE_TAG_*`` constants in the :mod:`stat` module.
2907
2908   The standard module :mod:`stat` defines functions and constants that are
2909   useful for extracting information from a :c:type:`stat` structure. (On
2910   Windows, some items are filled with dummy values.)
2911
2912   For backward compatibility, a :class:`stat_result` instance is also
2913   accessible as a tuple of at least 10 integers giving the most important (and
2914   portable) members of the :c:type:`stat` structure, in the order
2915   :attr:`st_mode`, :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`,
2916   :attr:`st_uid`, :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`,
2917   :attr:`st_mtime`, :attr:`st_ctime`. More items may be added at the end by
2918   some implementations. For compatibility with older Python versions,
2919   accessing :class:`stat_result` as a tuple always returns integers.
2920
2921   .. versionadded:: 3.3
2922      Added the :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and
2923      :attr:`st_ctime_ns` members.
2924
2925   .. versionadded:: 3.5
2926      Added the :attr:`st_file_attributes` member on Windows.
2927
2928   .. versionchanged:: 3.5
2929      Windows now returns the file index as :attr:`st_ino` when
2930      available.
2931
2932   .. versionadded:: 3.7
2933      Added the :attr:`st_fstype` member to Solaris/derivatives.
2934
2935   .. versionadded:: 3.8
2936      Added the :attr:`st_reparse_tag` member on Windows.
2937
2938   .. versionchanged:: 3.8
2939      On Windows, the :attr:`st_mode` member now identifies special
2940      files as :const:`S_IFCHR`, :const:`S_IFIFO` or :const:`S_IFBLK`
2941      as appropriate.
2942
2943.. function:: statvfs(path)
2944
2945   Perform a :c:func:`statvfs` system call on the given path.  The return value is
2946   an object whose attributes describe the filesystem on the given path, and
2947   correspond to the members of the :c:type:`statvfs` structure, namely:
2948   :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
2949   :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
2950   :attr:`f_flag`, :attr:`f_namemax`, :attr:`f_fsid`.
2951
2952   Two module-level constants are defined for the :attr:`f_flag` attribute's
2953   bit-flags: if :const:`ST_RDONLY` is set, the filesystem is mounted
2954   read-only, and if :const:`ST_NOSUID` is set, the semantics of
2955   setuid/setgid bits are disabled or not supported.
2956
2957   Additional module-level constants are defined for GNU/glibc based systems.
2958   These are :const:`ST_NODEV` (disallow access to device special files),
2959   :const:`ST_NOEXEC` (disallow program execution), :const:`ST_SYNCHRONOUS`
2960   (writes are synced at once), :const:`ST_MANDLOCK` (allow mandatory locks on an FS),
2961   :const:`ST_WRITE` (write on file/directory/symlink), :const:`ST_APPEND`
2962   (append-only file), :const:`ST_IMMUTABLE` (immutable file), :const:`ST_NOATIME`
2963   (do not update access times), :const:`ST_NODIRATIME` (do not update directory access
2964   times), :const:`ST_RELATIME` (update atime relative to mtime/ctime).
2965
2966   This function can support :ref:`specifying a file descriptor <path_fd>`.
2967
2968   .. availability:: Unix.
2969
2970   .. versionchanged:: 3.2
2971      The :const:`ST_RDONLY` and :const:`ST_NOSUID` constants were added.
2972
2973   .. versionadded:: 3.3
2974      Added support for specifying *path* as an open file descriptor.
2975
2976   .. versionchanged:: 3.4
2977      The :const:`ST_NODEV`, :const:`ST_NOEXEC`, :const:`ST_SYNCHRONOUS`,
2978      :const:`ST_MANDLOCK`, :const:`ST_WRITE`, :const:`ST_APPEND`,
2979      :const:`ST_IMMUTABLE`, :const:`ST_NOATIME`, :const:`ST_NODIRATIME`,
2980      and :const:`ST_RELATIME` constants were added.
2981
2982   .. versionchanged:: 3.6
2983      Accepts a :term:`path-like object`.
2984
2985   .. versionadded:: 3.7
2986      Added :attr:`f_fsid`.
2987
2988
2989.. data:: supports_dir_fd
2990
2991   A :class:`set` object indicating which functions in the :mod:`os`
2992   module accept an open file descriptor for their *dir_fd* parameter.
2993   Different platforms provide different features, and the underlying
2994   functionality Python uses to implement the *dir_fd* parameter is not
2995   available on all platforms Python supports.  For consistency's sake,
2996   functions that may support *dir_fd* always allow specifying the
2997   parameter, but will throw an exception if the functionality is used
2998   when it's not locally available. (Specifying ``None`` for *dir_fd*
2999   is always supported on all platforms.)
3000
3001   To check whether a particular function accepts an open file descriptor
3002   for its *dir_fd* parameter, use the ``in`` operator on ``supports_dir_fd``.
3003   As an example, this expression evaluates to ``True`` if :func:`os.stat`
3004   accepts open file descriptors for *dir_fd* on the local platform::
3005
3006       os.stat in os.supports_dir_fd
3007
3008   Currently *dir_fd* parameters only work on Unix platforms;
3009   none of them work on Windows.
3010
3011   .. versionadded:: 3.3
3012
3013
3014.. data:: supports_effective_ids
3015
3016   A :class:`set` object indicating whether :func:`os.access` permits
3017   specifying ``True`` for its *effective_ids* parameter on the local platform.
3018   (Specifying ``False`` for *effective_ids* is always supported on all
3019   platforms.)  If the local platform supports it, the collection will contain
3020   :func:`os.access`; otherwise it will be empty.
3021
3022   This expression evaluates to ``True`` if :func:`os.access` supports
3023   ``effective_ids=True`` on the local platform::
3024
3025       os.access in os.supports_effective_ids
3026
3027   Currently *effective_ids* is only supported on Unix platforms;
3028   it does not work on Windows.
3029
3030   .. versionadded:: 3.3
3031
3032
3033.. data:: supports_fd
3034
3035   A :class:`set` object indicating which functions in the
3036   :mod:`os` module permit specifying their *path* parameter as an open file
3037   descriptor on the local platform.  Different platforms provide different
3038   features, and the underlying functionality Python uses to accept open file
3039   descriptors as *path* arguments is not available on all platforms Python
3040   supports.
3041
3042   To determine whether a particular function permits specifying an open file
3043   descriptor for its *path* parameter, use the ``in`` operator on
3044   ``supports_fd``. As an example, this expression evaluates to ``True`` if
3045   :func:`os.chdir` accepts open file descriptors for *path* on your local
3046   platform::
3047
3048       os.chdir in os.supports_fd
3049
3050   .. versionadded:: 3.3
3051
3052
3053.. data:: supports_follow_symlinks
3054
3055   A :class:`set` object indicating which functions in the :mod:`os` module
3056   accept ``False`` for their *follow_symlinks* parameter on the local platform.
3057   Different platforms provide different features, and the underlying
3058   functionality Python uses to implement *follow_symlinks* is not available
3059   on all platforms Python supports.  For consistency's sake, functions that
3060   may support *follow_symlinks* always allow specifying the parameter, but
3061   will throw an exception if the functionality is used when it's not locally
3062   available.  (Specifying ``True`` for *follow_symlinks* is always supported
3063   on all platforms.)
3064
3065   To check whether a particular function accepts ``False`` for its
3066   *follow_symlinks* parameter, use the ``in`` operator on
3067   ``supports_follow_symlinks``.  As an example, this expression evaluates
3068   to ``True`` if you may specify ``follow_symlinks=False`` when calling
3069   :func:`os.stat` on the local platform::
3070
3071       os.stat in os.supports_follow_symlinks
3072
3073   .. versionadded:: 3.3
3074
3075
3076.. function:: symlink(src, dst, target_is_directory=False, *, dir_fd=None)
3077
3078   Create a symbolic link pointing to *src* named *dst*.
3079
3080   On Windows, a symlink represents either a file or a directory, and does not
3081   morph to the target dynamically.  If the target is present, the type of the
3082   symlink will be created to match. Otherwise, the symlink will be created
3083   as a directory if *target_is_directory* is ``True`` or a file symlink (the
3084   default) otherwise.  On non-Windows platforms, *target_is_directory* is ignored.
3085
3086   This function can support :ref:`paths relative to directory descriptors
3087   <dir_fd>`.
3088
3089   .. note::
3090
3091      On newer versions of Windows 10, unprivileged accounts can create symlinks
3092      if Developer Mode is enabled. When Developer Mode is not available/enabled,
3093      the *SeCreateSymbolicLinkPrivilege* privilege is required, or the process
3094      must be run as an administrator.
3095
3096
3097      :exc:`OSError` is raised when the function is called by an unprivileged
3098      user.
3099
3100   .. audit-event:: os.symlink src,dst,dir_fd os.symlink
3101
3102   .. availability:: Unix, Windows.
3103
3104      The function is limited on Emscripten and WASI, see
3105      :ref:`wasm-availability` for more information.
3106
3107   .. versionchanged:: 3.2
3108      Added support for Windows 6.0 (Vista) symbolic links.
3109
3110   .. versionadded:: 3.3
3111      Added the *dir_fd* argument, and now allow *target_is_directory*
3112      on non-Windows platforms.
3113
3114   .. versionchanged:: 3.6
3115      Accepts a :term:`path-like object` for *src* and *dst*.
3116
3117   .. versionchanged:: 3.8
3118      Added support for unelevated symlinks on Windows with Developer Mode.
3119
3120
3121.. function:: sync()
3122
3123   Force write of everything to disk.
3124
3125   .. availability:: Unix.
3126
3127   .. versionadded:: 3.3
3128
3129
3130.. function:: truncate(path, length)
3131
3132   Truncate the file corresponding to *path*, so that it is at most
3133   *length* bytes in size.
3134
3135   This function can support :ref:`specifying a file descriptor <path_fd>`.
3136
3137   .. audit-event:: os.truncate path,length os.truncate
3138
3139   .. availability:: Unix, Windows.
3140
3141   .. versionadded:: 3.3
3142
3143   .. versionchanged:: 3.5
3144      Added support for Windows
3145
3146   .. versionchanged:: 3.6
3147      Accepts a :term:`path-like object`.
3148
3149
3150.. function:: unlink(path, *, dir_fd=None)
3151
3152   Remove (delete) the file *path*.  This function is semantically
3153   identical to :func:`remove`; the ``unlink`` name is its
3154   traditional Unix name.  Please see the documentation for
3155   :func:`remove` for further information.
3156
3157   .. audit-event:: os.remove path,dir_fd os.unlink
3158
3159   .. versionadded:: 3.3
3160      The *dir_fd* parameter.
3161
3162   .. versionchanged:: 3.6
3163      Accepts a :term:`path-like object`.
3164
3165
3166.. function:: utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)
3167
3168   Set the access and modified times of the file specified by *path*.
3169
3170   :func:`utime` takes two optional parameters, *times* and *ns*.
3171   These specify the times set on *path* and are used as follows:
3172
3173   - If *ns* is specified,
3174     it must be a 2-tuple of the form ``(atime_ns, mtime_ns)``
3175     where each member is an int expressing nanoseconds.
3176   - If *times* is not ``None``,
3177     it must be a 2-tuple of the form ``(atime, mtime)``
3178     where each member is an int or float expressing seconds.
3179   - If *times* is ``None`` and *ns* is unspecified,
3180     this is equivalent to specifying ``ns=(atime_ns, mtime_ns)``
3181     where both times are the current time.
3182
3183   It is an error to specify tuples for both *times* and *ns*.
3184
3185   Note that the exact times you set here may not be returned by a subsequent
3186   :func:`~os.stat` call, depending on the resolution with which your operating
3187   system records access and modification times; see :func:`~os.stat`. The best
3188   way to preserve exact times is to use the *st_atime_ns* and *st_mtime_ns*
3189   fields from the :func:`os.stat` result object with the *ns* parameter to
3190   :func:`utime`.
3191
3192   This function can support :ref:`specifying a file descriptor <path_fd>`,
3193   :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
3194   following symlinks <follow_symlinks>`.
3195
3196   .. audit-event:: os.utime path,times,ns,dir_fd os.utime
3197
3198   .. versionadded:: 3.3
3199      Added support for specifying *path* as an open file descriptor,
3200      and the *dir_fd*, *follow_symlinks*, and *ns* parameters.
3201
3202   .. versionchanged:: 3.6
3203      Accepts a :term:`path-like object`.
3204
3205
3206.. function:: walk(top, topdown=True, onerror=None, followlinks=False)
3207
3208   .. index::
3209      single: directory; walking
3210      single: directory; traversal
3211
3212   Generate the file names in a directory tree by walking the tree
3213   either top-down or bottom-up. For each directory in the tree rooted at directory
3214   *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
3215   filenames)``.
3216
3217   *dirpath* is a string, the path to the directory.  *dirnames* is a list of the
3218   names of the subdirectories in *dirpath* (including symlinks to directories,
3219   and excluding ``'.'`` and ``'..'``).
3220   *filenames* is a list of the names of the non-directory files in *dirpath*.
3221   Note that the names in the lists contain no path components.  To get a full path
3222   (which begins with *top*) to a file or directory in *dirpath*, do
3223   ``os.path.join(dirpath, name)``.  Whether or not the lists are sorted
3224   depends on the file system.  If a file is removed from or added to the
3225   *dirpath* directory during generating the lists, whether a name for that
3226   file be included is unspecified.
3227
3228   If optional argument *topdown* is ``True`` or not specified, the triple for a
3229   directory is generated before the triples for any of its subdirectories
3230   (directories are generated top-down).  If *topdown* is ``False``, the triple
3231   for a directory is generated after the triples for all of its subdirectories
3232   (directories are generated bottom-up). No matter the value of *topdown*, the
3233   list of subdirectories is retrieved before the tuples for the directory and
3234   its subdirectories are generated.
3235
3236   When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
3237   (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
3238   recurse into the subdirectories whose names remain in *dirnames*; this can be
3239   used to prune the search, impose a specific order of visiting, or even to inform
3240   :func:`walk` about directories the caller creates or renames before it resumes
3241   :func:`walk` again.  Modifying *dirnames* when *topdown* is ``False`` has
3242   no effect on the behavior of the walk, because in bottom-up mode the directories
3243   in *dirnames* are generated before *dirpath* itself is generated.
3244
3245   By default, errors from the :func:`scandir` call are ignored.  If optional
3246   argument *onerror* is specified, it should be a function; it will be called with
3247   one argument, an :exc:`OSError` instance.  It can report the error to continue
3248   with the walk, or raise the exception to abort the walk.  Note that the filename
3249   is available as the ``filename`` attribute of the exception object.
3250
3251   By default, :func:`walk` will not walk down into symbolic links that resolve to
3252   directories. Set *followlinks* to ``True`` to visit directories pointed to by
3253   symlinks, on systems that support them.
3254
3255   .. note::
3256
3257      Be aware that setting *followlinks* to ``True`` can lead to infinite
3258      recursion if a link points to a parent directory of itself. :func:`walk`
3259      does not keep track of the directories it visited already.
3260
3261   .. note::
3262
3263      If you pass a relative pathname, don't change the current working directory
3264      between resumptions of :func:`walk`.  :func:`walk` never changes the current
3265      directory, and assumes that its caller doesn't either.
3266
3267   This example displays the number of bytes taken by non-directory files in each
3268   directory under the starting directory, except that it doesn't look under any
3269   CVS subdirectory::
3270
3271      import os
3272      from os.path import join, getsize
3273      for root, dirs, files in os.walk('python/Lib/email'):
3274          print(root, "consumes", end=" ")
3275          print(sum(getsize(join(root, name)) for name in files), end=" ")
3276          print("bytes in", len(files), "non-directory files")
3277          if 'CVS' in dirs:
3278              dirs.remove('CVS')  # don't visit CVS directories
3279
3280   In the next example (simple implementation of :func:`shutil.rmtree`),
3281   walking the tree bottom-up is essential, :func:`rmdir` doesn't allow
3282   deleting a directory before the directory is empty::
3283
3284      # Delete everything reachable from the directory named in "top",
3285      # assuming there are no symbolic links.
3286      # CAUTION:  This is dangerous!  For example, if top == '/', it
3287      # could delete all your disk files.
3288      import os
3289      for root, dirs, files in os.walk(top, topdown=False):
3290          for name in files:
3291              os.remove(os.path.join(root, name))
3292          for name in dirs:
3293              os.rmdir(os.path.join(root, name))
3294
3295   .. audit-event:: os.walk top,topdown,onerror,followlinks os.walk
3296
3297   .. versionchanged:: 3.5
3298      This function now calls :func:`os.scandir` instead of :func:`os.listdir`,
3299      making it faster by reducing the number of calls to :func:`os.stat`.
3300
3301   .. versionchanged:: 3.6
3302      Accepts a :term:`path-like object`.
3303
3304
3305.. function:: fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)
3306
3307   .. index::
3308      single: directory; walking
3309      single: directory; traversal
3310
3311   This behaves exactly like :func:`walk`, except that it yields a 4-tuple
3312   ``(dirpath, dirnames, filenames, dirfd)``, and it supports ``dir_fd``.
3313
3314   *dirpath*, *dirnames* and *filenames* are identical to :func:`walk` output,
3315   and *dirfd* is a file descriptor referring to the directory *dirpath*.
3316
3317   This function always supports :ref:`paths relative to directory descriptors
3318   <dir_fd>` and :ref:`not following symlinks <follow_symlinks>`.  Note however
3319   that, unlike other functions, the :func:`fwalk` default value for
3320   *follow_symlinks* is ``False``.
3321
3322   .. note::
3323
3324      Since :func:`fwalk` yields file descriptors, those are only valid until
3325      the next iteration step, so you should duplicate them (e.g. with
3326      :func:`dup`) if you want to keep them longer.
3327
3328   This example displays the number of bytes taken by non-directory files in each
3329   directory under the starting directory, except that it doesn't look under any
3330   CVS subdirectory::
3331
3332      import os
3333      for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
3334          print(root, "consumes", end="")
3335          print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
3336                end="")
3337          print("bytes in", len(files), "non-directory files")
3338          if 'CVS' in dirs:
3339              dirs.remove('CVS')  # don't visit CVS directories
3340
3341   In the next example, walking the tree bottom-up is essential:
3342   :func:`rmdir` doesn't allow deleting a directory before the directory is
3343   empty::
3344
3345      # Delete everything reachable from the directory named in "top",
3346      # assuming there are no symbolic links.
3347      # CAUTION:  This is dangerous!  For example, if top == '/', it
3348      # could delete all your disk files.
3349      import os
3350      for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
3351          for name in files:
3352              os.unlink(name, dir_fd=rootfd)
3353          for name in dirs:
3354              os.rmdir(name, dir_fd=rootfd)
3355
3356   .. audit-event:: os.fwalk top,topdown,onerror,follow_symlinks,dir_fd os.fwalk
3357
3358   .. availability:: Unix.
3359
3360   .. versionadded:: 3.3
3361
3362   .. versionchanged:: 3.6
3363      Accepts a :term:`path-like object`.
3364
3365   .. versionchanged:: 3.7
3366      Added support for :class:`bytes` paths.
3367
3368
3369.. function:: memfd_create(name[, flags=os.MFD_CLOEXEC])
3370
3371   Create an anonymous file and return a file descriptor that refers to it.
3372   *flags* must be one of the ``os.MFD_*`` constants available on the system
3373   (or a bitwise ORed combination of them).  By default, the new file
3374   descriptor is :ref:`non-inheritable <fd_inheritance>`.
3375
3376   The name supplied in *name* is used as a filename and will be displayed as
3377   the target of the corresponding symbolic link in the directory
3378   ``/proc/self/fd/``. The displayed name is always prefixed with ``memfd:``
3379   and serves only for debugging purposes. Names do not affect the behavior of
3380   the file descriptor, and as such multiple files can have the same name
3381   without any side effects.
3382
3383   .. availability:: Linux >= 3.17 with glibc >= 2.27.
3384
3385   .. versionadded:: 3.8
3386
3387
3388.. data:: MFD_CLOEXEC
3389          MFD_ALLOW_SEALING
3390          MFD_HUGETLB
3391          MFD_HUGE_SHIFT
3392          MFD_HUGE_MASK
3393          MFD_HUGE_64KB
3394          MFD_HUGE_512KB
3395          MFD_HUGE_1MB
3396          MFD_HUGE_2MB
3397          MFD_HUGE_8MB
3398          MFD_HUGE_16MB
3399          MFD_HUGE_32MB
3400          MFD_HUGE_256MB
3401          MFD_HUGE_512MB
3402          MFD_HUGE_1GB
3403          MFD_HUGE_2GB
3404          MFD_HUGE_16GB
3405
3406   These flags can be passed to :func:`memfd_create`.
3407
3408   .. availability:: Linux >= 3.17 with glibc >= 2.27
3409
3410      The ``MFD_HUGE*`` flags are only available since Linux 4.14.
3411
3412   .. versionadded:: 3.8
3413
3414
3415.. function:: eventfd(initval[, flags=os.EFD_CLOEXEC])
3416
3417   Create and return an event file descriptor. The file descriptors supports
3418   raw :func:`read` and :func:`write` with a buffer size of 8,
3419   :func:`~select.select`, :func:`~select.poll` and similar. See man page
3420   :manpage:`eventfd(2)` for more information.  By default, the
3421   new file descriptor is :ref:`non-inheritable <fd_inheritance>`.
3422
3423   *initval* is the initial value of the event counter. The initial value
3424   must be an 32 bit unsigned integer. Please note that the initial value is
3425   limited to a 32 bit unsigned int although the event counter is an unsigned
3426   64 bit integer with a maximum value of 2\ :sup:`64`\ -\ 2.
3427
3428   *flags* can be constructed from :const:`EFD_CLOEXEC`,
3429   :const:`EFD_NONBLOCK`, and :const:`EFD_SEMAPHORE`.
3430
3431   If :const:`EFD_SEMAPHORE` is specified and the event counter is non-zero,
3432   :func:`eventfd_read` returns 1 and decrements the counter by one.
3433
3434   If :const:`EFD_SEMAPHORE` is not specified and the event counter is
3435   non-zero, :func:`eventfd_read` returns the current event counter value and
3436   resets the counter to zero.
3437
3438   If the event counter is zero and :const:`EFD_NONBLOCK` is not
3439   specified, :func:`eventfd_read` blocks.
3440
3441   :func:`eventfd_write` increments the event counter. Write blocks if the
3442   write operation would increment the counter to a value larger than
3443   2\ :sup:`64`\ -\ 2.
3444
3445   Example::
3446
3447       import os
3448
3449       # semaphore with start value '1'
3450       fd = os.eventfd(1, os.EFD_SEMAPHORE | os.EFC_CLOEXEC)
3451       try:
3452           # acquire semaphore
3453           v = os.eventfd_read(fd)
3454           try:
3455               do_work()
3456           finally:
3457               # release semaphore
3458               os.eventfd_write(fd, v)
3459       finally:
3460           os.close(fd)
3461
3462   .. availability:: Linux >= 2.6.27 with glibc >= 2.8
3463
3464   .. versionadded:: 3.10
3465
3466.. function:: eventfd_read(fd)
3467
3468   Read value from an :func:`eventfd` file descriptor and return a 64 bit
3469   unsigned int. The function does not verify that *fd* is an :func:`eventfd`.
3470
3471   .. availability:: Linux >= 2.6.27
3472
3473   .. versionadded:: 3.10
3474
3475.. function:: eventfd_write(fd, value)
3476
3477   Add value to an :func:`eventfd` file descriptor. *value* must be a 64 bit
3478   unsigned int. The function does not verify that *fd* is an :func:`eventfd`.
3479
3480   .. availability:: Linux >= 2.6.27
3481
3482   .. versionadded:: 3.10
3483
3484.. data:: EFD_CLOEXEC
3485
3486   Set close-on-exec flag for new :func:`eventfd` file descriptor.
3487
3488   .. availability:: Linux >= 2.6.27
3489
3490   .. versionadded:: 3.10
3491
3492.. data:: EFD_NONBLOCK
3493
3494   Set :const:`O_NONBLOCK` status flag for new :func:`eventfd` file
3495   descriptor.
3496
3497   .. availability:: Linux >= 2.6.27
3498
3499   .. versionadded:: 3.10
3500
3501.. data:: EFD_SEMAPHORE
3502
3503   Provide semaphore-like semantics for reads from a :func:`eventfd` file
3504   descriptor. On read the internal counter is decremented by one.
3505
3506   .. availability:: Linux >= 2.6.30
3507
3508   .. versionadded:: 3.10
3509
3510
3511Linux extended attributes
3512~~~~~~~~~~~~~~~~~~~~~~~~~
3513
3514.. versionadded:: 3.3
3515
3516These functions are all available on Linux only.
3517
3518.. function:: getxattr(path, attribute, *, follow_symlinks=True)
3519
3520   Return the value of the extended filesystem attribute *attribute* for
3521   *path*. *attribute* can be bytes or str (directly or indirectly through the
3522   :class:`PathLike` interface). If it is str, it is encoded with the filesystem
3523   encoding.
3524
3525   This function can support :ref:`specifying a file descriptor <path_fd>` and
3526   :ref:`not following symlinks <follow_symlinks>`.
3527
3528   .. audit-event:: os.getxattr path,attribute os.getxattr
3529
3530   .. versionchanged:: 3.6
3531      Accepts a :term:`path-like object` for *path* and *attribute*.
3532
3533
3534.. function:: listxattr(path=None, *, follow_symlinks=True)
3535
3536   Return a list of the extended filesystem attributes on *path*.  The
3537   attributes in the list are represented as strings decoded with the filesystem
3538   encoding.  If *path* is ``None``, :func:`listxattr` will examine the current
3539   directory.
3540
3541   This function can support :ref:`specifying a file descriptor <path_fd>` and
3542   :ref:`not following symlinks <follow_symlinks>`.
3543
3544   .. audit-event:: os.listxattr path os.listxattr
3545
3546   .. versionchanged:: 3.6
3547      Accepts a :term:`path-like object`.
3548
3549
3550.. function:: removexattr(path, attribute, *, follow_symlinks=True)
3551
3552   Removes the extended filesystem attribute *attribute* from *path*.
3553   *attribute* should be bytes or str (directly or indirectly through the
3554   :class:`PathLike` interface). If it is a string, it is encoded
3555   with the :term:`filesystem encoding and error handler`.
3556
3557   This function can support :ref:`specifying a file descriptor <path_fd>` and
3558   :ref:`not following symlinks <follow_symlinks>`.
3559
3560   .. audit-event:: os.removexattr path,attribute os.removexattr
3561
3562   .. versionchanged:: 3.6
3563      Accepts a :term:`path-like object` for *path* and *attribute*.
3564
3565
3566.. function:: setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)
3567
3568   Set the extended filesystem attribute *attribute* on *path* to *value*.
3569   *attribute* must be a bytes or str with no embedded NULs (directly or
3570   indirectly through the :class:`PathLike` interface). If it is a str,
3571   it is encoded with the :term:`filesystem encoding and error handler`.  *flags* may be
3572   :data:`XATTR_REPLACE` or :data:`XATTR_CREATE`. If :data:`XATTR_REPLACE` is
3573   given and the attribute does not exist, ``ENODATA`` will be raised.
3574   If :data:`XATTR_CREATE` is given and the attribute already exists, the
3575   attribute will not be created and ``EEXISTS`` will be raised.
3576
3577   This function can support :ref:`specifying a file descriptor <path_fd>` and
3578   :ref:`not following symlinks <follow_symlinks>`.
3579
3580   .. note::
3581
3582      A bug in Linux kernel versions less than 2.6.39 caused the flags argument
3583      to be ignored on some filesystems.
3584
3585   .. audit-event:: os.setxattr path,attribute,value,flags os.setxattr
3586
3587   .. versionchanged:: 3.6
3588      Accepts a :term:`path-like object` for *path* and *attribute*.
3589
3590
3591.. data:: XATTR_SIZE_MAX
3592
3593   The maximum size the value of an extended attribute can be. Currently, this
3594   is 64 KiB on Linux.
3595
3596
3597.. data:: XATTR_CREATE
3598
3599   This is a possible value for the flags argument in :func:`setxattr`. It
3600   indicates the operation must create an attribute.
3601
3602
3603.. data:: XATTR_REPLACE
3604
3605   This is a possible value for the flags argument in :func:`setxattr`. It
3606   indicates the operation must replace an existing attribute.
3607
3608
3609.. _os-process:
3610
3611Process Management
3612------------------
3613
3614These functions may be used to create and manage processes.
3615
3616The various :func:`exec\* <execl>` functions take a list of arguments for the new
3617program loaded into the process.  In each case, the first of these arguments is
3618passed to the new program as its own name rather than as an argument a user may
3619have typed on a command line.  For the C programmer, this is the ``argv[0]``
3620passed to a program's :c:func:`main`.  For example, ``os.execv('/bin/echo',
3621['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
3622to be ignored.
3623
3624
3625.. function:: abort()
3626
3627   Generate a :const:`SIGABRT` signal to the current process.  On Unix, the default
3628   behavior is to produce a core dump; on Windows, the process immediately returns
3629   an exit code of ``3``.  Be aware that calling this function will not call the
3630   Python signal handler registered for :const:`SIGABRT` with
3631   :func:`signal.signal`.
3632
3633
3634.. function:: add_dll_directory(path)
3635
3636   Add a path to the DLL search path.
3637
3638   This search path is used when resolving dependencies for imported
3639   extension modules (the module itself is resolved through
3640   :data:`sys.path`), and also by :mod:`ctypes`.
3641
3642   Remove the directory by calling **close()** on the returned object
3643   or using it in a :keyword:`with` statement.
3644
3645   See the `Microsoft documentation
3646   <https://msdn.microsoft.com/44228cf2-6306-466c-8f16-f513cd3ba8b5>`_
3647   for more information about how DLLs are loaded.
3648
3649   .. audit-event:: os.add_dll_directory path os.add_dll_directory
3650
3651   .. availability:: Windows.
3652
3653   .. versionadded:: 3.8
3654      Previous versions of CPython would resolve DLLs using the default
3655      behavior for the current process. This led to inconsistencies,
3656      such as only sometimes searching :envvar:`PATH` or the current
3657      working directory, and OS functions such as ``AddDllDirectory``
3658      having no effect.
3659
3660      In 3.8, the two primary ways DLLs are loaded now explicitly
3661      override the process-wide behavior to ensure consistency. See the
3662      :ref:`porting notes <bpo-36085-whatsnew>` for information on
3663      updating libraries.
3664
3665
3666.. function:: execl(path, arg0, arg1, ...)
3667              execle(path, arg0, arg1, ..., env)
3668              execlp(file, arg0, arg1, ...)
3669              execlpe(file, arg0, arg1, ..., env)
3670              execv(path, args)
3671              execve(path, args, env)
3672              execvp(file, args)
3673              execvpe(file, args, env)
3674
3675   These functions all execute a new program, replacing the current process; they
3676   do not return.  On Unix, the new executable is loaded into the current process,
3677   and will have the same process id as the caller.  Errors will be reported as
3678   :exc:`OSError` exceptions.
3679
3680   The current process is replaced immediately. Open file objects and
3681   descriptors are not flushed, so if there may be data buffered
3682   on these open files, you should flush them using
3683   :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
3684   :func:`exec\* <execl>` function.
3685
3686   The "l" and "v" variants of the :func:`exec\* <execl>` functions differ in how
3687   command-line arguments are passed.  The "l" variants are perhaps the easiest
3688   to work with if the number of parameters is fixed when the code is written; the
3689   individual parameters simply become additional parameters to the :func:`execl\*`
3690   functions.  The "v" variants are good when the number of parameters is
3691   variable, with the arguments being passed in a list or tuple as the *args*
3692   parameter.  In either case, the arguments to the child process should start with
3693   the name of the command being run, but this is not enforced.
3694
3695   The variants which include a "p" near the end (:func:`execlp`,
3696   :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
3697   :envvar:`PATH` environment variable to locate the program *file*.  When the
3698   environment is being replaced (using one of the :func:`exec\*e <execl>` variants,
3699   discussed in the next paragraph), the new environment is used as the source of
3700   the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
3701   :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
3702   locate the executable; *path* must contain an appropriate absolute or relative
3703   path.
3704
3705   For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
3706   that these all end in "e"), the *env* parameter must be a mapping which is
3707   used to define the environment variables for the new process (these are used
3708   instead of the current process' environment); the functions :func:`execl`,
3709   :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
3710   inherit the environment of the current process.
3711
3712   For :func:`execve` on some platforms, *path* may also be specified as an open
3713   file descriptor.  This functionality may not be supported on your platform;
3714   you can check whether or not it is available using :data:`os.supports_fd`.
3715   If it is unavailable, using it will raise a :exc:`NotImplementedError`.
3716
3717   .. audit-event:: os.exec path,args,env os.execl
3718
3719   .. availability:: Unix, Windows, not Emscripten, not WASI.
3720
3721   .. versionadded:: 3.3
3722      Added support for specifying *path* as an open file descriptor
3723      for :func:`execve`.
3724
3725   .. versionchanged:: 3.6
3726      Accepts a :term:`path-like object`.
3727
3728.. function:: _exit(n)
3729
3730   Exit the process with status *n*, without calling cleanup handlers, flushing
3731   stdio buffers, etc.
3732
3733   .. note::
3734
3735      The standard way to exit is :func:`sys.exit(n) <sys.exit>`.  :func:`!_exit` should
3736      normally only be used in the child process after a :func:`fork`.
3737
3738The following exit codes are defined and can be used with :func:`_exit`,
3739although they are not required.  These are typically used for system programs
3740written in Python, such as a mail server's external command delivery program.
3741
3742.. note::
3743
3744   Some of these may not be available on all Unix platforms, since there is some
3745   variation.  These constants are defined where they are defined by the underlying
3746   platform.
3747
3748
3749.. data:: EX_OK
3750
3751   Exit code that means no error occurred. May be taken from the defined value of
3752   ``EXIT_SUCCESS`` on some platforms. Generally has a value of zero.
3753
3754   .. availability:: Unix, Windows.
3755
3756
3757.. data:: EX_USAGE
3758
3759   Exit code that means the command was used incorrectly, such as when the wrong
3760   number of arguments are given.
3761
3762   .. availability:: Unix, not Emscripten, not WASI.
3763
3764
3765.. data:: EX_DATAERR
3766
3767   Exit code that means the input data was incorrect.
3768
3769   .. availability:: Unix, not Emscripten, not WASI.
3770
3771
3772.. data:: EX_NOINPUT
3773
3774   Exit code that means an input file did not exist or was not readable.
3775
3776   .. availability:: Unix, not Emscripten, not WASI.
3777
3778
3779.. data:: EX_NOUSER
3780
3781   Exit code that means a specified user did not exist.
3782
3783   .. availability:: Unix, not Emscripten, not WASI.
3784
3785
3786.. data:: EX_NOHOST
3787
3788   Exit code that means a specified host did not exist.
3789
3790   .. availability:: Unix, not Emscripten, not WASI.
3791
3792
3793.. data:: EX_UNAVAILABLE
3794
3795   Exit code that means that a required service is unavailable.
3796
3797   .. availability:: Unix, not Emscripten, not WASI.
3798
3799
3800.. data:: EX_SOFTWARE
3801
3802   Exit code that means an internal software error was detected.
3803
3804   .. availability:: Unix, not Emscripten, not WASI.
3805
3806
3807.. data:: EX_OSERR
3808
3809   Exit code that means an operating system error was detected, such as the
3810   inability to fork or create a pipe.
3811
3812   .. availability:: Unix, not Emscripten, not WASI.
3813
3814
3815.. data:: EX_OSFILE
3816
3817   Exit code that means some system file did not exist, could not be opened, or had
3818   some other kind of error.
3819
3820   .. availability:: Unix, not Emscripten, not WASI.
3821
3822
3823.. data:: EX_CANTCREAT
3824
3825   Exit code that means a user specified output file could not be created.
3826
3827   .. availability:: Unix, not Emscripten, not WASI.
3828
3829
3830.. data:: EX_IOERR
3831
3832   Exit code that means that an error occurred while doing I/O on some file.
3833
3834   .. availability:: Unix, not Emscripten, not WASI.
3835
3836
3837.. data:: EX_TEMPFAIL
3838
3839   Exit code that means a temporary failure occurred.  This indicates something
3840   that may not really be an error, such as a network connection that couldn't be
3841   made during a retryable operation.
3842
3843   .. availability:: Unix, not Emscripten, not WASI.
3844
3845
3846.. data:: EX_PROTOCOL
3847
3848   Exit code that means that a protocol exchange was illegal, invalid, or not
3849   understood.
3850
3851   .. availability:: Unix, not Emscripten, not WASI.
3852
3853
3854.. data:: EX_NOPERM
3855
3856   Exit code that means that there were insufficient permissions to perform the
3857   operation (but not intended for file system problems).
3858
3859   .. availability:: Unix, not Emscripten, not WASI.
3860
3861
3862.. data:: EX_CONFIG
3863
3864   Exit code that means that some kind of configuration error occurred.
3865
3866   .. availability:: Unix, not Emscripten, not WASI.
3867
3868
3869.. data:: EX_NOTFOUND
3870
3871   Exit code that means something like "an entry was not found".
3872
3873   .. availability:: Unix, not Emscripten, not WASI.
3874
3875
3876.. function:: fork()
3877
3878   Fork a child process.  Return ``0`` in the child and the child's process id in the
3879   parent.  If an error occurs :exc:`OSError` is raised.
3880
3881   Note that some platforms including FreeBSD <= 6.3 and Cygwin have
3882   known issues when using ``fork()`` from a thread.
3883
3884   .. audit-event:: os.fork "" os.fork
3885
3886   .. versionchanged:: 3.8
3887      Calling ``fork()`` in a subinterpreter is no longer supported
3888      (:exc:`RuntimeError` is raised).
3889
3890   .. warning::
3891
3892      See :mod:`ssl` for applications that use the SSL module with fork().
3893
3894   .. availability:: Unix, not Emscripten, not WASI.
3895
3896
3897.. function:: forkpty()
3898
3899   Fork a child process, using a new pseudo-terminal as the child's controlling
3900   terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
3901   new child's process id in the parent, and *fd* is the file descriptor of the
3902   master end of the pseudo-terminal.  For a more portable approach, use the
3903   :mod:`pty` module.  If an error occurs :exc:`OSError` is raised.
3904
3905   .. audit-event:: os.forkpty "" os.forkpty
3906
3907   .. versionchanged:: 3.8
3908      Calling ``forkpty()`` in a subinterpreter is no longer supported
3909      (:exc:`RuntimeError` is raised).
3910
3911   .. availability:: Unix, not Emscripten, not WASI.
3912
3913
3914.. function:: kill(pid, sig, /)
3915
3916   .. index::
3917      single: process; killing
3918      single: process; signalling
3919
3920   Send signal *sig* to the process *pid*.  Constants for the specific signals
3921   available on the host platform are defined in the :mod:`signal` module.
3922
3923   Windows: The :data:`signal.CTRL_C_EVENT` and
3924   :data:`signal.CTRL_BREAK_EVENT` signals are special signals which can
3925   only be sent to console processes which share a common console window,
3926   e.g., some subprocesses. Any other value for *sig* will cause the process
3927   to be unconditionally killed by the TerminateProcess API, and the exit code
3928   will be set to *sig*. The Windows version of :func:`kill` additionally takes
3929   process handles to be killed.
3930
3931   See also :func:`signal.pthread_kill`.
3932
3933   .. audit-event:: os.kill pid,sig os.kill
3934
3935   .. availability:: Unix, Windows, not Emscripten, not WASI.
3936
3937   .. versionadded:: 3.2
3938      Windows support.
3939
3940
3941.. function:: killpg(pgid, sig, /)
3942
3943   .. index::
3944      single: process; killing
3945      single: process; signalling
3946
3947   Send the signal *sig* to the process group *pgid*.
3948
3949   .. audit-event:: os.killpg pgid,sig os.killpg
3950
3951   .. availability:: Unix, not Emscripten, not WASI.
3952
3953
3954.. function:: nice(increment, /)
3955
3956   Add *increment* to the process's "niceness".  Return the new niceness.
3957
3958   .. availability:: Unix, not Emscripten, not WASI.
3959
3960
3961.. function:: pidfd_open(pid, flags=0)
3962
3963   Return a file descriptor referring to the process *pid*.  This descriptor can
3964   be used to perform process management without races and signals.  The *flags*
3965   argument is provided for future extensions; no flag values are currently
3966   defined.
3967
3968   See the :manpage:`pidfd_open(2)` man page for more details.
3969
3970   .. availability:: Linux >= 5.3
3971   .. versionadded:: 3.9
3972
3973
3974.. function:: plock(op, /)
3975
3976   Lock program segments into memory.  The value of *op* (defined in
3977   ``<sys/lock.h>``) determines which segments are locked.
3978
3979   .. availability:: Unix, not Emscripten, not WASI.
3980
3981
3982.. function:: popen(cmd, mode='r', buffering=-1)
3983
3984   Open a pipe to or from command *cmd*.
3985   The return value is an open file object
3986   connected to the pipe, which can be read or written depending on whether *mode*
3987   is ``'r'`` (default) or ``'w'``.
3988   The *buffering* argument have the same meaning as
3989   the corresponding argument to the built-in :func:`open` function. The
3990   returned file object reads or writes text strings rather than bytes.
3991
3992   The ``close`` method returns :const:`None` if the subprocess exited
3993   successfully, or the subprocess's return code if there was an
3994   error. On POSIX systems, if the return code is positive it
3995   represents the return value of the process left-shifted by one
3996   byte.  If the return code is negative, the process was terminated
3997   by the signal given by the negated value of the return code.  (For
3998   example, the return value might be ``- signal.SIGKILL`` if the
3999   subprocess was killed.)  On Windows systems, the return value
4000   contains the signed integer return code from the child process.
4001
4002   On Unix, :func:`waitstatus_to_exitcode` can be used to convert the ``close``
4003   method result (exit status) into an exit code if it is not ``None``. On
4004   Windows, the ``close`` method result is directly the exit code
4005   (or ``None``).
4006
4007   This is implemented using :class:`subprocess.Popen`; see that class's
4008   documentation for more powerful ways to manage and communicate with
4009   subprocesses.
4010
4011   .. availability:: not Emscripten, not WASI.
4012
4013   .. note::
4014      The :ref:`Python UTF-8 Mode <utf8-mode>` affects encodings used
4015      for *cmd* and pipe contents.
4016
4017      :func:`popen` is a simple wrapper around :class:`subprocess.Popen`.
4018      Use :class:`subprocess.Popen` or :func:`subprocess.run` to
4019      control options like encodings.
4020
4021
4022.. function:: posix_spawn(path, argv, env, *, file_actions=None, \
4023                          setpgroup=None, resetids=False, setsid=False, setsigmask=(), \
4024                          setsigdef=(), scheduler=None)
4025
4026   Wraps the :c:func:`posix_spawn` C library API for use from Python.
4027
4028   Most users should use :func:`subprocess.run` instead of :func:`posix_spawn`.
4029
4030   The positional-only arguments *path*, *args*, and *env* are similar to
4031   :func:`execve`.
4032
4033   The *path* parameter is the path to the executable file.  The *path* should
4034   contain a directory.  Use :func:`posix_spawnp` to pass an executable file
4035   without directory.
4036
4037   The *file_actions* argument may be a sequence of tuples describing actions
4038   to take on specific file descriptors in the child process between the C
4039   library implementation's :c:func:`fork` and :c:func:`exec` steps.
4040   The first item in each tuple must be one of the three type indicator
4041   listed below describing the remaining tuple elements:
4042
4043   .. data:: POSIX_SPAWN_OPEN
4044
4045      (``os.POSIX_SPAWN_OPEN``, *fd*, *path*, *flags*, *mode*)
4046
4047      Performs ``os.dup2(os.open(path, flags, mode), fd)``.
4048
4049   .. data:: POSIX_SPAWN_CLOSE
4050
4051      (``os.POSIX_SPAWN_CLOSE``, *fd*)
4052
4053      Performs ``os.close(fd)``.
4054
4055   .. data:: POSIX_SPAWN_DUP2
4056
4057      (``os.POSIX_SPAWN_DUP2``, *fd*, *new_fd*)
4058
4059      Performs ``os.dup2(fd, new_fd)``.
4060
4061   These tuples correspond to the C library
4062   :c:func:`posix_spawn_file_actions_addopen`,
4063   :c:func:`posix_spawn_file_actions_addclose`, and
4064   :c:func:`posix_spawn_file_actions_adddup2` API calls used to prepare
4065   for the :c:func:`posix_spawn` call itself.
4066
4067   The *setpgroup* argument will set the process group of the child to the value
4068   specified. If the value specified is 0, the child's process group ID will be
4069   made the same as its process ID. If the value of *setpgroup* is not set, the
4070   child will inherit the parent's process group ID. This argument corresponds
4071   to the C library :c:data:`POSIX_SPAWN_SETPGROUP` flag.
4072
4073   If the *resetids* argument is ``True`` it will reset the effective UID and
4074   GID of the child to the real UID and GID of the parent process. If the
4075   argument is ``False``, then the child retains the effective UID and GID of
4076   the parent. In either case, if the set-user-ID and set-group-ID permission
4077   bits are enabled on the executable file, their effect will override the
4078   setting of the effective UID and GID. This argument corresponds to the C
4079   library :c:data:`POSIX_SPAWN_RESETIDS` flag.
4080
4081   If the *setsid* argument is ``True``, it will create a new session ID
4082   for ``posix_spawn``. *setsid* requires :c:data:`POSIX_SPAWN_SETSID`
4083   or :c:data:`POSIX_SPAWN_SETSID_NP` flag. Otherwise, :exc:`NotImplementedError`
4084   is raised.
4085
4086   The *setsigmask* argument will set the signal mask to the signal set
4087   specified. If the parameter is not used, then the child inherits the
4088   parent's signal mask. This argument corresponds to the C library
4089   :c:data:`POSIX_SPAWN_SETSIGMASK` flag.
4090
4091   The *sigdef* argument will reset the disposition of all signals in the set
4092   specified. This argument corresponds to the C library
4093   :c:data:`POSIX_SPAWN_SETSIGDEF` flag.
4094
4095   The *scheduler* argument must be a tuple containing the (optional) scheduler
4096   policy and an instance of :class:`sched_param` with the scheduler parameters.
4097   A value of ``None`` in the place of the scheduler policy indicates that is
4098   not being provided. This argument is a combination of the C library
4099   :c:data:`POSIX_SPAWN_SETSCHEDPARAM` and :c:data:`POSIX_SPAWN_SETSCHEDULER`
4100   flags.
4101
4102   .. audit-event:: os.posix_spawn path,argv,env os.posix_spawn
4103
4104   .. versionadded:: 3.8
4105
4106   .. availability:: Unix, not Emscripten, not WASI.
4107
4108.. function:: posix_spawnp(path, argv, env, *, file_actions=None, \
4109                          setpgroup=None, resetids=False, setsid=False, setsigmask=(), \
4110                          setsigdef=(), scheduler=None)
4111
4112   Wraps the :c:func:`posix_spawnp` C library API for use from Python.
4113
4114   Similar to :func:`posix_spawn` except that the system searches
4115   for the *executable* file in the list of directories specified by the
4116   :envvar:`PATH` environment variable (in the same way as for ``execvp(3)``).
4117
4118   .. audit-event:: os.posix_spawn path,argv,env os.posix_spawnp
4119
4120   .. versionadded:: 3.8
4121
4122   .. availability:: POSIX, not Emscripten, not WASI.
4123
4124      See :func:`posix_spawn` documentation.
4125
4126
4127.. function:: register_at_fork(*, before=None, after_in_parent=None, \
4128                               after_in_child=None)
4129
4130   Register callables to be executed when a new child process is forked
4131   using :func:`os.fork` or similar process cloning APIs.
4132   The parameters are optional and keyword-only.
4133   Each specifies a different call point.
4134
4135   * *before* is a function called before forking a child process.
4136   * *after_in_parent* is a function called from the parent process
4137     after forking a child process.
4138   * *after_in_child* is a function called from the child process.
4139
4140   These calls are only made if control is expected to return to the
4141   Python interpreter.  A typical :mod:`subprocess` launch will not
4142   trigger them as the child is not going to re-enter the interpreter.
4143
4144   Functions registered for execution before forking are called in
4145   reverse registration order.  Functions registered for execution
4146   after forking (either in the parent or in the child) are called
4147   in registration order.
4148
4149   Note that :c:func:`fork` calls made by third-party C code may not
4150   call those functions, unless it explicitly calls :c:func:`PyOS_BeforeFork`,
4151   :c:func:`PyOS_AfterFork_Parent` and :c:func:`PyOS_AfterFork_Child`.
4152
4153   There is no way to unregister a function.
4154
4155   .. availability:: Unix, not Emscripten, not WASI.
4156
4157   .. versionadded:: 3.7
4158
4159
4160.. function:: spawnl(mode, path, ...)
4161              spawnle(mode, path, ..., env)
4162              spawnlp(mode, file, ...)
4163              spawnlpe(mode, file, ..., env)
4164              spawnv(mode, path, args)
4165              spawnve(mode, path, args, env)
4166              spawnvp(mode, file, args)
4167              spawnvpe(mode, file, args, env)
4168
4169   Execute the program *path* in a new process.
4170
4171   (Note that the :mod:`subprocess` module provides more powerful facilities for
4172   spawning new processes and retrieving their results; using that module is
4173   preferable to using these functions.  Check especially the
4174   :ref:`subprocess-replacements` section.)
4175
4176   If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
4177   process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
4178   exits normally, or ``-signal``, where *signal* is the signal that killed the
4179   process.  On Windows, the process id will actually be the process handle, so can
4180   be used with the :func:`waitpid` function.
4181
4182   Note on VxWorks, this function doesn't return ``-signal`` when the new process is
4183   killed. Instead it raises OSError exception.
4184
4185   The "l" and "v" variants of the :func:`spawn\* <spawnl>` functions differ in how
4186   command-line arguments are passed.  The "l" variants are perhaps the easiest
4187   to work with if the number of parameters is fixed when the code is written; the
4188   individual parameters simply become additional parameters to the
4189   :func:`spawnl\*` functions.  The "v" variants are good when the number of
4190   parameters is variable, with the arguments being passed in a list or tuple as
4191   the *args* parameter.  In either case, the arguments to the child process must
4192   start with the name of the command being run.
4193
4194   The variants which include a second "p" near the end (:func:`spawnlp`,
4195   :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
4196   :envvar:`PATH` environment variable to locate the program *file*.  When the
4197   environment is being replaced (using one of the :func:`spawn\*e <spawnl>` variants,
4198   discussed in the next paragraph), the new environment is used as the source of
4199   the :envvar:`PATH` variable.  The other variants, :func:`spawnl`,
4200   :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
4201   :envvar:`PATH` variable to locate the executable; *path* must contain an
4202   appropriate absolute or relative path.
4203
4204   For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
4205   (note that these all end in "e"), the *env* parameter must be a mapping
4206   which is used to define the environment variables for the new process (they are
4207   used instead of the current process' environment); the functions
4208   :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
4209   the new process to inherit the environment of the current process.  Note that
4210   keys and values in the *env* dictionary must be strings; invalid keys or
4211   values will cause the function to fail, with a return value of ``127``.
4212
4213   As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
4214   equivalent::
4215
4216      import os
4217      os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
4218
4219      L = ['cp', 'index.html', '/dev/null']
4220      os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
4221
4222   .. audit-event:: os.spawn mode,path,args,env os.spawnl
4223
4224   .. availability:: Unix, Windows, not Emscripten, not WASI.
4225
4226      :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
4227      and :func:`spawnvpe` are not available on Windows.  :func:`spawnle` and
4228      :func:`spawnve` are not thread-safe on Windows; we advise you to use the
4229      :mod:`subprocess` module instead.
4230
4231   .. versionchanged:: 3.6
4232      Accepts a :term:`path-like object`.
4233
4234
4235.. data:: P_NOWAIT
4236          P_NOWAITO
4237
4238   Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
4239   functions.  If either of these values is given, the :func:`spawn\*` functions
4240   will return as soon as the new process has been created, with the process id as
4241   the return value.
4242
4243   .. availability:: Unix, Windows.
4244
4245
4246.. data:: P_WAIT
4247
4248   Possible value for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
4249   functions.  If this is given as *mode*, the :func:`spawn\*` functions will not
4250   return until the new process has run to completion and will return the exit code
4251   of the process the run is successful, or ``-signal`` if a signal kills the
4252   process.
4253
4254   .. availability:: Unix, Windows.
4255
4256
4257.. data:: P_DETACH
4258          P_OVERLAY
4259
4260   Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
4261   functions.  These are less portable than those listed above. :const:`P_DETACH`
4262   is similar to :const:`P_NOWAIT`, but the new process is detached from the
4263   console of the calling process. If :const:`P_OVERLAY` is used, the current
4264   process will be replaced; the :func:`spawn\* <spawnl>` function will not return.
4265
4266   .. availability:: Windows.
4267
4268
4269.. function:: startfile(path, [operation], [arguments], [cwd], [show_cmd])
4270
4271   Start a file with its associated application.
4272
4273   When *operation* is not specified or ``'open'``, this acts like double-clicking
4274   the file in Windows Explorer, or giving the file name as an argument to the
4275   :program:`start` command from the interactive command shell: the file is opened
4276   with whatever application (if any) its extension is associated.
4277
4278   When another *operation* is given, it must be a "command verb" that specifies
4279   what should be done with the file. Common verbs documented by Microsoft are
4280   ``'print'`` and  ``'edit'`` (to be used on files) as well as ``'explore'`` and
4281   ``'find'`` (to be used on directories).
4282
4283   When launching an application, specify *arguments* to be passed as a single
4284   string. This argument may have no effect when using this function to launch a
4285   document.
4286
4287   The default working directory is inherited, but may be overridden by the *cwd*
4288   argument. This should be an absolute path. A relative *path* will be resolved
4289   against this argument.
4290
4291   Use *show_cmd* to override the default window style. Whether this has any
4292   effect will depend on the application being launched. Values are integers as
4293   supported by the Win32 :c:func:`ShellExecute` function.
4294
4295   :func:`startfile` returns as soon as the associated application is launched.
4296   There is no option to wait for the application to close, and no way to retrieve
4297   the application's exit status.  The *path* parameter is relative to the current
4298   directory or *cwd*.  If you want to use an absolute path, make sure the first
4299   character is not a slash (``'/'``)  Use :mod:`pathlib` or the
4300   :func:`os.path.normpath` function to ensure that paths are properly encoded for
4301   Win32.
4302
4303   To reduce interpreter startup overhead, the Win32 :c:func:`ShellExecute`
4304   function is not resolved until this function is first called.  If the function
4305   cannot be resolved, :exc:`NotImplementedError` will be raised.
4306
4307   .. audit-event:: os.startfile path,operation os.startfile
4308
4309   .. audit-event:: os.startfile/2 path,operation,arguments,cwd,show_cmd os.startfile
4310
4311   .. availability:: Windows.
4312
4313   .. versionchanged:: 3.10
4314      Added the *arguments*, *cwd* and *show_cmd* arguments, and the
4315      ``os.startfile/2`` audit event.
4316
4317
4318.. function:: system(command)
4319
4320   Execute the command (a string) in a subshell.  This is implemented by calling
4321   the Standard C function :c:func:`system`, and has the same limitations.
4322   Changes to :data:`sys.stdin`, etc. are not reflected in the environment of
4323   the executed command. If *command* generates any output, it will be sent to
4324   the interpreter standard output stream. The C standard does not
4325   specify the meaning of the return value of the C function, so the return
4326   value of the Python function is system-dependent.
4327
4328   On Unix, the return value is the exit status of the process encoded in the
4329   format specified for :func:`wait`.
4330
4331   On Windows, the return value is that returned by the system shell after
4332   running *command*.  The shell is given by the Windows environment variable
4333   :envvar:`COMSPEC`: it is usually :program:`cmd.exe`, which returns the exit
4334   status of the command run; on systems using a non-native shell, consult your
4335   shell documentation.
4336
4337   The :mod:`subprocess` module provides more powerful facilities for spawning
4338   new processes and retrieving their results; using that module is preferable
4339   to using this function.  See the :ref:`subprocess-replacements` section in
4340   the :mod:`subprocess` documentation for some helpful recipes.
4341
4342   On Unix, :func:`waitstatus_to_exitcode` can be used to convert the result
4343   (exit status) into an exit code. On Windows, the result is directly the exit
4344   code.
4345
4346   .. audit-event:: os.system command os.system
4347
4348   .. availability:: Unix, Windows, not Emscripten, not WASI.
4349
4350
4351.. function:: times()
4352
4353   Returns the current global process times.
4354   The return value is an object with five attributes:
4355
4356   * :attr:`!user` - user time
4357   * :attr:`!system` - system time
4358   * :attr:`!children_user` - user time of all child processes
4359   * :attr:`!children_system` - system time of all child processes
4360   * :attr:`!elapsed` - elapsed real time since a fixed point in the past
4361
4362   For backwards compatibility, this object also behaves like a five-tuple
4363   containing :attr:`!user`, :attr:`!system`, :attr:`!children_user`,
4364   :attr:`!children_system`, and :attr:`!elapsed` in that order.
4365
4366   See the Unix manual page
4367   :manpage:`times(2)` and `times(3) <https://man.freebsd.org/cgi/man.cgi?time(3)>`_ manual page on Unix or `the GetProcessTimes MSDN
4368   <https://docs.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes>`_
4369   on Windows. On Windows, only :attr:`!user` and :attr:`!system` are known; the other attributes are zero.
4370
4371   .. availability:: Unix, Windows.
4372
4373   .. versionchanged:: 3.3
4374      Return type changed from a tuple to a tuple-like object
4375      with named attributes.
4376
4377
4378.. function:: wait()
4379
4380   Wait for completion of a child process, and return a tuple containing its pid
4381   and exit status indication: a 16-bit number, whose low byte is the signal number
4382   that killed the process, and whose high byte is the exit status (if the signal
4383   number is zero); the high bit of the low byte is set if a core file was
4384   produced.
4385
4386   If there are no children that could be waited for, :exc:`ChildProcessError`
4387   is raised.
4388
4389   :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
4390   exit code.
4391
4392   .. availability:: Unix, not Emscripten, not WASI.
4393
4394   .. seealso::
4395
4396      The other :func:`!wait*` functions documented below can be used to wait for the
4397      completion of a specific child process and have more options.
4398      :func:`waitpid` is the only one also available on Windows.
4399
4400
4401.. function:: waitid(idtype, id, options, /)
4402
4403   Wait for the completion of a child process.
4404
4405   *idtype* can be :data:`P_PID`, :data:`P_PGID`, :data:`P_ALL`, or (on Linux) :data:`P_PIDFD`.
4406   The interpretation of *id* depends on it; see their individual descriptions.
4407
4408   *options* is an OR combination of flags.  At least one of :data:`WEXITED`,
4409   :data:`WSTOPPED` or :data:`WCONTINUED` is required;
4410   :data:`WNOHANG` and :data:`WNOWAIT` are additional optional flags.
4411
4412   The return value is an object representing the data contained in the
4413   :c:type:`!siginfo_t` structure with the following attributes:
4414
4415   * :attr:`!si_pid` (process ID)
4416   * :attr:`!si_uid` (real user ID of the child)
4417   * :attr:`!si_signo` (always :data:`~signal.SIGCHLD`)
4418   * :attr:`!si_status` (the exit status or signal number, depending on :attr:`!si_code`)
4419   * :attr:`!si_code` (see :data:`CLD_EXITED` for possible values)
4420
4421   If :data:`WNOHANG` is specified and there are no matching children in the
4422   requested state, ``None`` is returned.
4423   Otherwise, if there are no matching children
4424   that could be waited for, :exc:`ChildProcessError` is raised.
4425
4426   .. availability:: Unix, not Emscripten, not WASI.
4427
4428   .. versionadded:: 3.3
4429
4430
4431.. function:: waitpid(pid, options, /)
4432
4433   The details of this function differ on Unix and Windows.
4434
4435   On Unix: Wait for completion of a child process given by process id *pid*, and
4436   return a tuple containing its process id and exit status indication (encoded as
4437   for :func:`wait`).  The semantics of the call are affected by the value of the
4438   integer *options*, which should be ``0`` for normal operation.
4439
4440   If *pid* is greater than ``0``, :func:`waitpid` requests status information for
4441   that specific process.  If *pid* is ``0``, the request is for the status of any
4442   child in the process group of the current process.  If *pid* is ``-1``, the
4443   request pertains to any child of the current process.  If *pid* is less than
4444   ``-1``, status is requested for any process in the process group ``-pid`` (the
4445   absolute value of *pid*).
4446
4447   *options* is an OR combination of flags.  If it contains :data:`WNOHANG` and
4448   there are no matching children in the requested state, ``(0, 0)`` is
4449   returned.  Otherwise, if there are no matching children that could be waited
4450   for, :exc:`ChildProcessError` is raised.  Other options that can be used are
4451   :data:`WUNTRACED` and :data:`WCONTINUED`.
4452
4453   On Windows: Wait for completion of a process given by process handle *pid*, and
4454   return a tuple containing *pid*, and its exit status shifted left by 8 bits
4455   (shifting makes cross-platform use of the function easier). A *pid* less than or
4456   equal to ``0`` has no special meaning on Windows, and raises an exception. The
4457   value of integer *options* has no effect. *pid* can refer to any process whose
4458   id is known, not necessarily a child process. The :func:`spawn\* <spawnl>`
4459   functions called with :const:`P_NOWAIT` return suitable process handles.
4460
4461   :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
4462   exit code.
4463
4464   .. availability:: Unix, Windows, not Emscripten, not WASI.
4465
4466   .. versionchanged:: 3.5
4467      If the system call is interrupted and the signal handler does not raise an
4468      exception, the function now retries the system call instead of raising an
4469      :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
4470
4471
4472.. function:: wait3(options)
4473
4474   Similar to :func:`waitpid`, except no process id argument is given and a
4475   3-element tuple containing the child's process id, exit status indication,
4476   and resource usage information is returned.  Refer to
4477   :func:`resource.getrusage` for details on resource usage information.  The
4478   *options* argument is the same as that provided to :func:`waitpid` and
4479   :func:`wait4`.
4480
4481   :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
4482   exitcode.
4483
4484   .. availability:: Unix, not Emscripten, not WASI.
4485
4486
4487.. function:: wait4(pid, options)
4488
4489   Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
4490   process id, exit status indication, and resource usage information is
4491   returned.  Refer to :func:`resource.getrusage` for details on resource usage
4492   information.  The arguments to :func:`wait4` are the same as those provided
4493   to :func:`waitpid`.
4494
4495   :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
4496   exitcode.
4497
4498   .. availability:: Unix, not Emscripten, not WASI.
4499
4500
4501.. data:: P_PID
4502          P_PGID
4503          P_ALL
4504          P_PIDFD
4505
4506   These are the possible values for *idtype* in :func:`waitid`. They affect
4507   how *id* is interpreted:
4508
4509   * :data:`!P_PID` - wait for the child whose PID is *id*.
4510   * :data:`!P_PGID` - wait for any child whose progress group ID is *id*.
4511   * :data:`!P_ALL` - wait for any child; *id* is ignored.
4512   * :data:`!P_PIDFD` - wait for the child identified by the file descriptor
4513     *id* (a process file descriptor created with :func:`pidfd_open`).
4514
4515   .. availability:: Unix, not Emscripten, not WASI.
4516
4517   .. note:: :data:`!P_PIDFD` is only available on Linux >= 5.4.
4518
4519   .. versionadded:: 3.3
4520   .. versionadded:: 3.9
4521      The :data:`!P_PIDFD` constant.
4522
4523
4524.. data:: WCONTINUED
4525
4526   This *options* flag for :func:`waitpid`, :func:`wait3`, :func:`wait4`, and
4527   :func:`waitid` causes child processes to be reported if they have been
4528   continued from a job control stop since they were last reported.
4529
4530   .. availability:: Unix, not Emscripten, not WASI.
4531
4532
4533.. data:: WEXITED
4534
4535   This *options* flag for :func:`waitid` causes child processes that have terminated to
4536   be reported.
4537
4538   The other ``wait*`` functions always report children that have terminated,
4539   so this option is not available for them.
4540
4541   .. availability:: Unix, not Emscripten, not WASI.
4542
4543   .. versionadded:: 3.3
4544
4545
4546.. data:: WSTOPPED
4547
4548   This *options* flag for :func:`waitid` causes child processes that have been stopped
4549   by the delivery of a signal to be reported.
4550
4551   This option is not available for the other ``wait*`` functions.
4552
4553   .. availability:: Unix, not Emscripten, not WASI.
4554
4555   .. versionadded:: 3.3
4556
4557
4558.. data:: WUNTRACED
4559
4560   This *options* flag for :func:`waitpid`, :func:`wait3`, and :func:`wait4` causes
4561   child processes to also be reported if they have been stopped but their
4562   current state has not been reported since they were stopped.
4563
4564   This option is not available for :func:`waitid`.
4565
4566   .. availability:: Unix, not Emscripten, not WASI.
4567
4568
4569.. data:: WNOHANG
4570
4571   This *options* flag causes :func:`waitpid`, :func:`wait3`, :func:`wait4`, and
4572   :func:`waitid` to return right away if no child process status is available
4573   immediately.
4574
4575   .. availability:: Unix, not Emscripten, not WASI.
4576
4577
4578.. data:: WNOWAIT
4579
4580   This *options* flag causes :func:`waitid` to leave the child in a waitable state, so that
4581   a later :func:`!wait*` call can be used to retrieve the child status information again.
4582
4583   This option is not available for the other ``wait*`` functions.
4584
4585   .. availability:: Unix, not Emscripten, not WASI.
4586
4587
4588.. data:: CLD_EXITED
4589          CLD_KILLED
4590          CLD_DUMPED
4591          CLD_TRAPPED
4592          CLD_STOPPED
4593          CLD_CONTINUED
4594
4595   These are the possible values for :attr:`!si_code` in the result returned by
4596   :func:`waitid`.
4597
4598   .. availability:: Unix, not Emscripten, not WASI.
4599
4600   .. versionadded:: 3.3
4601
4602   .. versionchanged:: 3.9
4603      Added :data:`CLD_KILLED` and :data:`CLD_STOPPED` values.
4604
4605
4606.. function:: waitstatus_to_exitcode(status)
4607
4608   Convert a wait status to an exit code.
4609
4610   On Unix:
4611
4612   * If the process exited normally (if ``WIFEXITED(status)`` is true),
4613     return the process exit status (return ``WEXITSTATUS(status)``):
4614     result greater than or equal to 0.
4615   * If the process was terminated by a signal (if ``WIFSIGNALED(status)`` is
4616     true), return ``-signum`` where *signum* is the number of the signal that
4617     caused the process to terminate (return ``-WTERMSIG(status)``):
4618     result less than 0.
4619   * Otherwise, raise a :exc:`ValueError`.
4620
4621   On Windows, return *status* shifted right by 8 bits.
4622
4623   On Unix, if the process is being traced or if :func:`waitpid` was called
4624   with :data:`WUNTRACED` option, the caller must first check if
4625   ``WIFSTOPPED(status)`` is true. This function must not be called if
4626   ``WIFSTOPPED(status)`` is true.
4627
4628   .. seealso::
4629
4630      :func:`WIFEXITED`, :func:`WEXITSTATUS`, :func:`WIFSIGNALED`,
4631      :func:`WTERMSIG`, :func:`WIFSTOPPED`, :func:`WSTOPSIG` functions.
4632
4633   .. availability:: Unix, Windows, not Emscripten, not WASI.
4634
4635   .. versionadded:: 3.9
4636
4637
4638The following functions take a process status code as returned by
4639:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter.  They may be
4640used to determine the disposition of a process.
4641
4642.. function:: WCOREDUMP(status, /)
4643
4644   Return ``True`` if a core dump was generated for the process, otherwise
4645   return ``False``.
4646
4647   This function should be employed only if :func:`WIFSIGNALED` is true.
4648
4649   .. availability:: Unix, not Emscripten, not WASI.
4650
4651
4652.. function:: WIFCONTINUED(status)
4653
4654   Return ``True`` if a stopped child has been resumed by delivery of
4655   :data:`~signal.SIGCONT` (if the process has been continued from a job
4656   control stop), otherwise return ``False``.
4657
4658   See :data:`WCONTINUED` option.
4659
4660   .. availability:: Unix, not Emscripten, not WASI.
4661
4662
4663.. function:: WIFSTOPPED(status)
4664
4665   Return ``True`` if the process was stopped by delivery of a signal,
4666   otherwise return ``False``.
4667
4668   :func:`WIFSTOPPED` only returns ``True`` if the :func:`waitpid` call was
4669   done using :data:`WUNTRACED` option or when the process is being traced (see
4670   :manpage:`ptrace(2)`).
4671
4672   .. availability:: Unix, not Emscripten, not WASI.
4673
4674.. function:: WIFSIGNALED(status)
4675
4676   Return ``True`` if the process was terminated by a signal, otherwise return
4677   ``False``.
4678
4679   .. availability:: Unix, not Emscripten, not WASI.
4680
4681
4682.. function:: WIFEXITED(status)
4683
4684   Return ``True`` if the process exited terminated normally, that is,
4685   by calling ``exit()`` or ``_exit()``, or by returning from ``main()``;
4686   otherwise return ``False``.
4687
4688   .. availability:: Unix, not Emscripten, not WASI.
4689
4690
4691.. function:: WEXITSTATUS(status)
4692
4693   Return the process exit status.
4694
4695   This function should be employed only if :func:`WIFEXITED` is true.
4696
4697   .. availability:: Unix, not Emscripten, not WASI.
4698
4699
4700.. function:: WSTOPSIG(status)
4701
4702   Return the signal which caused the process to stop.
4703
4704   This function should be employed only if :func:`WIFSTOPPED` is true.
4705
4706   .. availability:: Unix, not Emscripten, not WASI.
4707
4708
4709.. function:: WTERMSIG(status)
4710
4711   Return the number of the signal that caused the process to terminate.
4712
4713   This function should be employed only if :func:`WIFSIGNALED` is true.
4714
4715   .. availability:: Unix, not Emscripten, not WASI.
4716
4717
4718Interface to the scheduler
4719--------------------------
4720
4721These functions control how a process is allocated CPU time by the operating
4722system. They are only available on some Unix platforms. For more detailed
4723information, consult your Unix manpages.
4724
4725.. versionadded:: 3.3
4726
4727The following scheduling policies are exposed if they are supported by the
4728operating system.
4729
4730.. data:: SCHED_OTHER
4731
4732   The default scheduling policy.
4733
4734.. data:: SCHED_BATCH
4735
4736   Scheduling policy for CPU-intensive processes that tries to preserve
4737   interactivity on the rest of the computer.
4738
4739.. data:: SCHED_IDLE
4740
4741   Scheduling policy for extremely low priority background tasks.
4742
4743.. data:: SCHED_SPORADIC
4744
4745   Scheduling policy for sporadic server programs.
4746
4747.. data:: SCHED_FIFO
4748
4749   A First In First Out scheduling policy.
4750
4751.. data:: SCHED_RR
4752
4753   A round-robin scheduling policy.
4754
4755.. data:: SCHED_RESET_ON_FORK
4756
4757   This flag can be OR'ed with any other scheduling policy. When a process with
4758   this flag set forks, its child's scheduling policy and priority are reset to
4759   the default.
4760
4761
4762.. class:: sched_param(sched_priority)
4763
4764   This class represents tunable scheduling parameters used in
4765   :func:`sched_setparam`, :func:`sched_setscheduler`, and
4766   :func:`sched_getparam`. It is immutable.
4767
4768   At the moment, there is only one possible parameter:
4769
4770   .. attribute:: sched_priority
4771
4772      The scheduling priority for a scheduling policy.
4773
4774
4775.. function:: sched_get_priority_min(policy)
4776
4777   Get the minimum priority value for *policy*. *policy* is one of the
4778   scheduling policy constants above.
4779
4780
4781.. function:: sched_get_priority_max(policy)
4782
4783   Get the maximum priority value for *policy*. *policy* is one of the
4784   scheduling policy constants above.
4785
4786
4787.. function:: sched_setscheduler(pid, policy, param, /)
4788
4789   Set the scheduling policy for the process with PID *pid*. A *pid* of 0 means
4790   the calling process. *policy* is one of the scheduling policy constants
4791   above. *param* is a :class:`sched_param` instance.
4792
4793
4794.. function:: sched_getscheduler(pid, /)
4795
4796   Return the scheduling policy for the process with PID *pid*. A *pid* of 0
4797   means the calling process. The result is one of the scheduling policy
4798   constants above.
4799
4800
4801.. function:: sched_setparam(pid, param, /)
4802
4803   Set the scheduling parameters for the process with PID *pid*. A *pid* of 0 means
4804   the calling process. *param* is a :class:`sched_param` instance.
4805
4806
4807.. function:: sched_getparam(pid, /)
4808
4809   Return the scheduling parameters as a :class:`sched_param` instance for the
4810   process with PID *pid*. A *pid* of 0 means the calling process.
4811
4812
4813.. function:: sched_rr_get_interval(pid, /)
4814
4815   Return the round-robin quantum in seconds for the process with PID *pid*. A
4816   *pid* of 0 means the calling process.
4817
4818
4819.. function:: sched_yield()
4820
4821   Voluntarily relinquish the CPU.
4822
4823
4824.. function:: sched_setaffinity(pid, mask, /)
4825
4826   Restrict the process with PID *pid* (or the current process if zero) to a
4827   set of CPUs.  *mask* is an iterable of integers representing the set of
4828   CPUs to which the process should be restricted.
4829
4830
4831.. function:: sched_getaffinity(pid, /)
4832
4833   Return the set of CPUs the process with PID *pid* (or the current process
4834   if zero) is restricted to.
4835
4836
4837.. _os-path:
4838
4839Miscellaneous System Information
4840--------------------------------
4841
4842
4843.. function:: confstr(name, /)
4844
4845   Return string-valued system configuration values. *name* specifies the
4846   configuration value to retrieve; it may be a string which is the name of a
4847   defined system value; these names are specified in a number of standards (POSIX,
4848   Unix 95, Unix 98, and others).  Some platforms define additional names as well.
4849   The names known to the host operating system are given as the keys of the
4850   ``confstr_names`` dictionary.  For configuration variables not included in that
4851   mapping, passing an integer for *name* is also accepted.
4852
4853   If the configuration value specified by *name* isn't defined, ``None`` is
4854   returned.
4855
4856   If *name* is a string and is not known, :exc:`ValueError` is raised.  If a
4857   specific value for *name* is not supported by the host system, even if it is
4858   included in ``confstr_names``, an :exc:`OSError` is raised with
4859   :const:`errno.EINVAL` for the error number.
4860
4861   .. availability:: Unix.
4862
4863
4864.. data:: confstr_names
4865
4866   Dictionary mapping names accepted by :func:`confstr` to the integer values
4867   defined for those names by the host operating system. This can be used to
4868   determine the set of names known to the system.
4869
4870   .. availability:: Unix.
4871
4872
4873.. function:: cpu_count()
4874
4875   Return the number of CPUs in the system. Returns ``None`` if undetermined.
4876
4877   This number is not equivalent to the number of CPUs the current process can
4878   use.  The number of usable CPUs can be obtained with
4879   ``len(os.sched_getaffinity(0))``
4880
4881
4882   .. versionadded:: 3.4
4883
4884
4885.. function:: getloadavg()
4886
4887   Return the number of processes in the system run queue averaged over the last
4888   1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
4889   unobtainable.
4890
4891   .. availability:: Unix.
4892
4893
4894.. function:: sysconf(name, /)
4895
4896   Return integer-valued system configuration values. If the configuration value
4897   specified by *name* isn't defined, ``-1`` is returned.  The comments regarding
4898   the *name* parameter for :func:`confstr` apply here as well; the dictionary that
4899   provides information on the known names is given by ``sysconf_names``.
4900
4901   .. availability:: Unix.
4902
4903
4904.. data:: sysconf_names
4905
4906   Dictionary mapping names accepted by :func:`sysconf` to the integer values
4907   defined for those names by the host operating system. This can be used to
4908   determine the set of names known to the system.
4909
4910   .. availability:: Unix.
4911
4912   .. versionchanged:: 3.11
4913      Add ``'SC_MINSIGSTKSZ'`` name.
4914
4915The following data values are used to support path manipulation operations.  These
4916are defined for all platforms.
4917
4918Higher-level operations on pathnames are defined in the :mod:`os.path` module.
4919
4920
4921.. index:: single: . (dot); in pathnames
4922.. data:: curdir
4923
4924   The constant string used by the operating system to refer to the current
4925   directory. This is ``'.'`` for Windows and POSIX. Also available via
4926   :mod:`os.path`.
4927
4928
4929.. index:: single: ..; in pathnames
4930.. data:: pardir
4931
4932   The constant string used by the operating system to refer to the parent
4933   directory. This is ``'..'`` for Windows and POSIX. Also available via
4934   :mod:`os.path`.
4935
4936
4937.. index:: single: / (slash); in pathnames
4938.. index:: single: \ (backslash); in pathnames (Windows)
4939.. data:: sep
4940
4941   The character used by the operating system to separate pathname components.
4942   This is ``'/'`` for POSIX and ``'\\'`` for Windows.  Note that knowing this
4943   is not sufficient to be able to parse or concatenate pathnames --- use
4944   :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
4945   useful. Also available via :mod:`os.path`.
4946
4947
4948.. index:: single: / (slash); in pathnames
4949.. data:: altsep
4950
4951   An alternative character used by the operating system to separate pathname
4952   components, or ``None`` if only one separator character exists.  This is set to
4953   ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
4954   :mod:`os.path`.
4955
4956
4957.. index:: single: . (dot); in pathnames
4958.. data:: extsep
4959
4960   The character which separates the base filename from the extension; for example,
4961   the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
4962
4963
4964.. index:: single: : (colon); path separator (POSIX)
4965   single: ; (semicolon)
4966.. data:: pathsep
4967
4968   The character conventionally used by the operating system to separate search
4969   path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
4970   Windows. Also available via :mod:`os.path`.
4971
4972
4973.. data:: defpath
4974
4975   The default search path used by :func:`exec\*p\* <execl>` and
4976   :func:`spawn\*p\* <spawnl>` if the environment doesn't have a ``'PATH'``
4977   key. Also available via :mod:`os.path`.
4978
4979
4980.. data:: linesep
4981
4982   The string used to separate (or, rather, terminate) lines on the current
4983   platform.  This may be a single character, such as ``'\n'`` for POSIX, or
4984   multiple characters, for example, ``'\r\n'`` for Windows. Do not use
4985   *os.linesep* as a line terminator when writing files opened in text mode (the
4986   default); use a single ``'\n'`` instead, on all platforms.
4987
4988
4989.. data:: devnull
4990
4991   The file path of the null device. For example: ``'/dev/null'`` for
4992   POSIX, ``'nul'`` for Windows.  Also available via :mod:`os.path`.
4993
4994.. data:: RTLD_LAZY
4995          RTLD_NOW
4996          RTLD_GLOBAL
4997          RTLD_LOCAL
4998          RTLD_NODELETE
4999          RTLD_NOLOAD
5000          RTLD_DEEPBIND
5001
5002   Flags for use with the :func:`~sys.setdlopenflags` and
5003   :func:`~sys.getdlopenflags` functions.  See the Unix manual page
5004   :manpage:`dlopen(3)` for what the different flags mean.
5005
5006   .. versionadded:: 3.3
5007
5008
5009Random numbers
5010--------------
5011
5012
5013.. function:: getrandom(size, flags=0)
5014
5015   Get up to *size* random bytes. The function can return less bytes than
5016   requested.
5017
5018   These bytes can be used to seed user-space random number generators or for
5019   cryptographic purposes.
5020
5021   ``getrandom()`` relies on entropy gathered from device drivers and other
5022   sources of environmental noise. Unnecessarily reading large quantities of
5023   data will have a negative impact on  other users  of the ``/dev/random`` and
5024   ``/dev/urandom`` devices.
5025
5026   The flags argument is a bit mask that can contain zero or more of the
5027   following values ORed together: :py:data:`os.GRND_RANDOM` and
5028   :py:data:`GRND_NONBLOCK`.
5029
5030   See also the `Linux getrandom() manual page
5031   <https://man7.org/linux/man-pages/man2/getrandom.2.html>`_.
5032
5033   .. availability:: Linux >= 3.17.
5034
5035   .. versionadded:: 3.6
5036
5037.. function:: urandom(size, /)
5038
5039   Return a bytestring of *size* random bytes suitable for cryptographic use.
5040
5041   This function returns random bytes from an OS-specific randomness source.  The
5042   returned data should be unpredictable enough for cryptographic applications,
5043   though its exact quality depends on the OS implementation.
5044
5045   On Linux, if the ``getrandom()`` syscall is available, it is used in
5046   blocking mode: block until the system urandom entropy pool is initialized
5047   (128 bits of entropy are collected by the kernel). See the :pep:`524` for
5048   the rationale. On Linux, the :func:`getrandom` function can be used to get
5049   random bytes in non-blocking mode (using the :data:`GRND_NONBLOCK` flag) or
5050   to poll until the system urandom entropy pool is initialized.
5051
5052   On a Unix-like system, random bytes are read from the ``/dev/urandom``
5053   device. If the ``/dev/urandom`` device is not available or not readable, the
5054   :exc:`NotImplementedError` exception is raised.
5055
5056   On Windows, it will use ``BCryptGenRandom()``.
5057
5058   .. seealso::
5059      The :mod:`secrets` module provides higher level functions. For an
5060      easy-to-use interface to the random number generator provided by your
5061      platform, please see :class:`random.SystemRandom`.
5062
5063   .. versionchanged:: 3.6.0
5064      On Linux, ``getrandom()`` is now used in blocking mode to increase the
5065      security.
5066
5067   .. versionchanged:: 3.5.2
5068      On Linux, if the ``getrandom()`` syscall blocks (the urandom entropy pool
5069      is not initialized yet), fall back on reading ``/dev/urandom``.
5070
5071   .. versionchanged:: 3.5
5072      On Linux 3.17 and newer, the ``getrandom()`` syscall is now used
5073      when available.  On OpenBSD 5.6 and newer, the C ``getentropy()``
5074      function is now used. These functions avoid the usage of an internal file
5075      descriptor.
5076
5077   .. versionchanged:: 3.11
5078      On Windows, ``BCryptGenRandom()`` is used instead of ``CryptGenRandom()``
5079      which is deprecated.
5080
5081.. data:: GRND_NONBLOCK
5082
5083   By  default, when reading from ``/dev/random``, :func:`getrandom` blocks if
5084   no random bytes are available, and when reading from ``/dev/urandom``, it blocks
5085   if the entropy pool has not yet been initialized.
5086
5087   If the :py:data:`GRND_NONBLOCK` flag is set, then :func:`getrandom` does not
5088   block in these cases, but instead immediately raises :exc:`BlockingIOError`.
5089
5090   .. versionadded:: 3.6
5091
5092.. data:: GRND_RANDOM
5093
5094   If  this  bit  is  set,  then  random bytes are drawn from the
5095   ``/dev/random`` pool instead of the ``/dev/urandom`` pool.
5096
5097   .. versionadded:: 3.6
5098