Debian Codegraph @

Doc/library/os.rst

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