Debian Codegraph @

Doc/library/os.rst

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