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