Debian Codegraph @

Doc/library/os.rst

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