Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(5)

Delta Between Two Patch Sets: Doc/library/os.rst

Issue 26826: Expose new copy_file_range() syscal in os module and use it to improve shutils.copy()
Left Patch Set: Created 3 years, 7 months ago
Right Patch Set: Created 3 years, 7 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « configure.ac ('k') | Lib/test/test_os.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 :mod:`os` --- Miscellaneous operating system interfaces 1 :mod:`os` --- Miscellaneous operating system interfaces
2 ======================================================= 2 =======================================================
3 3
4 .. module:: os 4 .. module:: os
5 :synopsis: Miscellaneous operating system interfaces. 5 :synopsis: Miscellaneous operating system interfaces.
6 6
7 7
8 This module provides a portable way of using operating system dependent 8 This module provides a portable way of using operating system dependent
9 functionality. If you just want to read or write a file see :func:`open`, if 9 functionality. If you just want to read or write a file see :func:`open`, if
10 you want to manipulate paths, see the :mod:`os.path` module, and if you want to 10 you want to manipulate paths, see the :mod:`os.path` module, and if you want to
(...skipping 60 matching lines...) Expand 10 before | Expand all | Expand 10 after
71 ------------------------------------------------------------- 71 -------------------------------------------------------------
72 72
73 In Python, file names, command line arguments, and environment variables are 73 In Python, file names, command line arguments, and environment variables are
74 represented using the string type. On some systems, decoding these strings to 74 represented using the string type. On some systems, decoding these strings to
75 and from bytes is necessary before passing them to the operating system. Python 75 and from bytes is necessary before passing them to the operating system. Python
76 uses the file system encoding to perform this conversion (see 76 uses the file system encoding to perform this conversion (see
77 :func:`sys.getfilesystemencoding`). 77 :func:`sys.getfilesystemencoding`).
78 78
79 .. versionchanged:: 3.1 79 .. versionchanged:: 3.1
80 On some systems, conversion using the file system encoding may fail. In this 80 On some systems, conversion using the file system encoding may fail. In this
81 case, Python uses the ``surrogateescape`` encoding error handler, which means 81 case, Python uses the :ref:`surrogateescape encoding error handler
82 that undecodable bytes are replaced by a Unicode character U+DCxx on 82 <surrogateescape>`, which means that undecodable bytes are replaced by a
83 decoding, and these are again translated to the original byte on encoding. 83 Unicode character U+DCxx on decoding, and these are again translated to the
84 original byte on encoding.
84 85
85 86
86 The file system encoding must guarantee to successfully decode all bytes 87 The file system encoding must guarantee to successfully decode all bytes
87 below 128. If the file system encoding fails to provide this guarantee, API 88 below 128. If the file system encoding fails to provide this guarantee, API
88 functions may raise UnicodeErrors. 89 functions may raise UnicodeErrors.
89 90
90 91
91 .. _os-procinfo: 92 .. _os-procinfo:
92 93
93 Process Parameters 94 Process Parameters
(...skipping 82 matching lines...) Expand 10 before | Expand all | Expand 10 after
176 177
177 178
178 .. function:: fsdecode(filename) 179 .. function:: fsdecode(filename)
179 180
180 Decode *filename* from the filesystem encoding with ``'surrogateescape'`` 181 Decode *filename* from the filesystem encoding with ``'surrogateescape'``
181 error handler, or ``'strict'`` on Windows; return :class:`str` unchanged. 182 error handler, or ``'strict'`` on Windows; return :class:`str` unchanged.
182 183
183 :func:`fsencode` is the reverse function. 184 :func:`fsencode` is the reverse function.
184 185
185 .. versionadded:: 3.2 186 .. versionadded:: 3.2
187
188
189 .. function:: fspath(path)
190
191 Return the string representation of the path.
192
193 If :class:`str` or :class:`bytes` is passed in, it is returned unchanged;
194 otherwise, the result of calling ``type(path).__fspath__`` is returned, or an
195 exception is raised.
186 196
187 197
188 .. function:: getenv(key, default=None) 198 .. function:: getenv(key, default=None)
189 199
190 Return the value of the environment variable *key* if it exists, or 200 Return the value of the environment variable *key* if it exists, or
191 *default* if it doesn't. *key*, *default* and the result are str. 201 *default* if it doesn't. *key*, *default* and the result are str.
192 202
193 On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding` 203 On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding`
194 and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you 204 and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you
195 would like to use a different encoding. 205 would like to use a different encoding.
(...skipping 108 matching lines...) Expand 10 before | Expand all | Expand 10 after
304 314
305 Availability: Unix. 315 Availability: Unix.
306 316
307 317
308 .. function:: getpid() 318 .. function:: getpid()
309 319
310 .. index:: single: process; id 320 .. index:: single: process; id
311 321
312 Return the current process id. 322 Return the current process id.
313 323
314 Availability: Unix, Windows.
315
316 324
317 .. function:: getppid() 325 .. function:: getppid()
318 326
319 .. index:: single: process; id of parent 327 .. index:: single: process; id of parent
320 328
321 Return the parent's process id. When the parent process has exited, on Unix 329 Return the parent's process id. When the parent process has exited, on Unix
322 the id returned is the one of the init process (1), on Windows it is still 330 the id returned is the one of the init process (1), on Windows it is still
323 the same id, which may be already reused by another process. 331 the same id, which may be already reused by another process.
324 332
325 Availability: Unix, Windows. 333 Availability: Unix, Windows.
(...skipping 216 matching lines...) Expand 10 before | Expand all | Expand 10 after
542 Availability: Unix. 550 Availability: Unix.
543 551
544 552
545 .. placed in this section since it relates to errno.... a little weak 553 .. placed in this section since it relates to errno.... a little weak
546 .. function:: strerror(code) 554 .. function:: strerror(code)
547 555
548 Return the error message corresponding to the error code in *code*. 556 Return the error message corresponding to the error code in *code*.
549 On platforms where :c:func:`strerror` returns ``NULL`` when given an unknown 557 On platforms where :c:func:`strerror` returns ``NULL`` when given an unknown
550 error number, :exc:`ValueError` is raised. 558 error number, :exc:`ValueError` is raised.
551 559
552 Availability: Unix, Windows.
553
554 560
555 .. data:: supports_bytes_environ 561 .. data:: supports_bytes_environ
556 562
557 ``True`` if the native OS type of the environment is bytes (eg. ``False`` on 563 ``True`` if the native OS type of the environment is bytes (eg. ``False`` on
558 Windows). 564 Windows).
559 565
560 .. versionadded:: 3.2 566 .. versionadded:: 3.2
561 567
562 568
563 .. function:: umask(mask) 569 .. function:: umask(mask)
564 570
565 Set the current numeric umask and return the previous umask. 571 Set the current numeric umask and return the previous umask.
566
567 Availability: Unix, Windows.
568 572
569 573
570 .. function:: uname() 574 .. function:: uname()
571 575
572 .. index:: 576 .. index::
573 single: gethostname() (in module socket) 577 single: gethostname() (in module socket)
574 single: gethostbyaddr() (in module socket) 578 single: gethostbyaddr() (in module socket)
575 579
576 Returns information identifying the current operating system. 580 Returns information identifying the current operating system.
577 The return value is an object with five attributes: 581 The return value is an object with five attributes:
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
649 The :meth:`~io.IOBase.fileno` method can be used to obtain the file descriptor 653 The :meth:`~io.IOBase.fileno` method can be used to obtain the file descriptor
650 associated with a :term:`file object` when required. Note that using the file 654 associated with a :term:`file object` when required. Note that using the file
651 descriptor directly will bypass the file object methods, ignoring aspects such 655 descriptor directly will bypass the file object methods, ignoring aspects such
652 as internal buffering of data. 656 as internal buffering of data.
653 657
654 658
655 .. function:: close(fd) 659 .. function:: close(fd)
656 660
657 Close file descriptor *fd*. 661 Close file descriptor *fd*.
658 662
659 Availability: Unix, Windows.
660
661 .. note:: 663 .. note::
662 664
663 This function is intended for low-level I/O and must be applied to a file 665 This function is intended for low-level I/O and must be applied to a file
664 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "fi le 666 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "fi le
665 object" returned by the built-in function :func:`open` or by :func:`popen` or 667 object" returned by the built-in function :func:`open` or by :func:`popen` or
666 :func:`fdopen`, use its :meth:`~io.IOBase.close` method. 668 :func:`fdopen`, use its :meth:`~io.IOBase.close` method.
667 669
668 670
669 .. function:: closerange(fd_low, fd_high) 671 .. function:: closerange(fd_low, fd_high)
670 672
671 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive) , 673 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive) ,
672 ignoring errors. Equivalent to (but much faster than):: 674 ignoring errors. Equivalent to (but much faster than)::
673 675
674 for fd in range(fd_low, fd_high): 676 for fd in range(fd_low, fd_high):
675 try: 677 try:
676 os.close(fd) 678 os.close(fd)
677 except OSError: 679 except OSError:
678 pass 680 pass
679 681
680 Availability: Unix, Windows. 682
681 683 .. function:: copy_file_range(src, dst, count, offset_src=None, offset_dst=None)
682
683 .. function:: copy_file_range(src, dst, count, offset_src=None, offset_dst=None, flags=0)
684 684
685 Copy *count* bytes from file descriptor *src*, starting from offset 685 Copy *count* bytes from file descriptor *src*, starting from offset
686 *offset_src*, to file descriptor *dst*, starting from offset *offset_dst*. 686 *offset_src*, to file descriptor *dst*, starting from offset *offset_dst*.
687 If *offset_src* is None, then *src* is read from the current position; 687 If *offset_src* is None, then *src* is read from the current position;
688 respectively for *offset_dst*. The files pointed by *src* and *dst* 688 respectively for *offset_dst*. The files pointed by *src* and *dst*
689 must reside in the same filesystem, otherwise a :exc:`OSError` is 689 must reside in the same filesystem, otherwise a :exc:`OSError` is
690 raised with :attr:`~OSError.errno` set to :data:`errno.EXDEV`. 690 raised with :attr:`~OSError.errno` set to :data:`errno.EXDEV`.
691 691
692 This copy is done without using any user space buffers, and some 692 This copy is done without using any user space buffers, and some
693 filesystems could implement optimizations. The copy is done as if 693 filesystems could implement optimizations. The copy is done as if
694 both files are opened as binary. 694 both files are opened as binary.
695 695
696 The *flags* argument is provided for compatibility with the only currently
697 supported implementation (Linux >=4.5) to allow for future extensions, and
698 currently can only be 0.
699
700 The return value is the amount of bytes copied. This could be less than the 696 The return value is the amount of bytes copied. This could be less than the
701 amount requested. 697 amount requested.
702 698
703 Availability: some recent flavors of Unix (see the man page 699 Availability: Linux 4.5, released May 2016 (see the man page
704 :manpage:`copy_file_range(2)` for further information). 700 :manpage:`copy_file_range(2)` for further information).
705 701
706 .. versionadded:: 3.6 702 .. versionadded:: 3.6
707 703
708 .. function:: device_encoding(fd) 704 .. function:: device_encoding(fd)
709 705
710 Return a string describing the encoding of the device associated with *fd* 706 Return a string describing the encoding of the device associated with *fd*
711 if it is connected to a terminal; else return :const:`None`. 707 if it is connected to a terminal; else return :const:`None`.
712 708
713 709
714 .. function:: dup(fd) 710 .. function:: dup(fd)
715 711
716 Return a duplicate of file descriptor *fd*. The new file descriptor is 712 Return a duplicate of file descriptor *fd*. The new file descriptor is
717 :ref:`non-inheritable <fd_inheritance>`. 713 :ref:`non-inheritable <fd_inheritance>`.
718 714
719 On Windows, when duplicating a standard stream (0: stdin, 1: stdout, 715 On Windows, when duplicating a standard stream (0: stdin, 1: stdout,
720 2: stderr), the new file descriptor is :ref:`inheritable 716 2: stderr), the new file descriptor is :ref:`inheritable
721 <fd_inheritance>`. 717 <fd_inheritance>`.
722 718
723 Availability: Unix, Windows.
724
725 .. versionchanged:: 3.4 719 .. versionchanged:: 3.4
726 The new file descriptor is now non-inheritable. 720 The new file descriptor is now non-inheritable.
727 721
728 722
729 .. function:: dup2(fd, fd2, inheritable=True) 723 .. function:: dup2(fd, fd2, inheritable=True)
730 724
731 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessar y. 725 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessar y.
732 The file descriptor *fd2* is :ref:`inheritable <fd_inheritance>` by default, 726 The file descriptor *fd2* is :ref:`inheritable <fd_inheritance>` by default,
733 or non-inheritable if *inheritable* is ``False``. 727 or non-inheritable if *inheritable* is ``False``.
734
735 Availability: Unix, Windows.
736 728
737 .. versionchanged:: 3.4 729 .. versionchanged:: 3.4
738 Add the optional *inheritable* parameter. 730 Add the optional *inheritable* parameter.
739 731
740 732
741 .. function:: fchmod(fd, mode) 733 .. function:: fchmod(fd, mode)
742 734
743 Change the mode of the file given by *fd* to the numeric *mode*. See the 735 Change the mode of the file given by *fd* to the numeric *mode*. See the
744 docs for :func:`chmod` for possible values of *mode*. As of Python 3.3, this 736 docs for :func:`chmod` for possible values of *mode*. As of Python 3.3, this
745 is equivalent to ``os.chmod(fd, mode)``. 737 is equivalent to ``os.chmod(fd, mode)``.
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
792 784
793 Get the status of the file descriptor *fd*. Return a :class:`stat_result` 785 Get the status of the file descriptor *fd*. Return a :class:`stat_result`
794 object. 786 object.
795 787
796 As of Python 3.3, this is equivalent to ``os.stat(fd)``. 788 As of Python 3.3, this is equivalent to ``os.stat(fd)``.
797 789
798 .. seealso:: 790 .. seealso::
799 791
800 The :func:`.stat` function. 792 The :func:`.stat` function.
801 793
802 Availability: Unix, Windows.
803
804 794
805 .. function:: fstatvfs(fd) 795 .. function:: fstatvfs(fd)
806 796
807 Return information about the filesystem containing the file associated with 797 Return information about the filesystem containing the file associated with
808 file descriptor *fd*, like :func:`statvfs`. As of Python 3.3, this is 798 file descriptor *fd*, like :func:`statvfs`. As of Python 3.3, this is
809 equivalent to ``os.statvfs(fd)``. 799 equivalent to ``os.statvfs(fd)``.
810 800
811 Availability: Unix. 801 Availability: Unix.
812 802
813 803
814 .. function:: fsync(fd) 804 .. function:: fsync(fd)
815 805
816 Force write of file with filedescriptor *fd* to disk. On Unix, this calls th e 806 Force write of file with filedescriptor *fd* to disk. On Unix, this calls th e
817 native :c:func:`fsync` function; on Windows, the MS :c:func:`_commit` functio n. 807 native :c:func:`fsync` function; on Windows, the MS :c:func:`_commit` functio n.
818 808
819 If you're starting with a buffered Python :term:`file object` *f*, first do 809 If you're starting with a buffered Python :term:`file object` *f*, first do
820 ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all inter nal 810 ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all inter nal
821 buffers associated with *f* are written to disk. 811 buffers associated with *f* are written to disk.
822 812
823 Availability: Unix, Windows. 813 Availability: Unix, Windows.
824 814
825 815
826 .. function:: ftruncate(fd, length) 816 .. function:: ftruncate(fd, length)
827 817
828 Truncate the file corresponding to file descriptor *fd*, so that it is at 818 Truncate the file corresponding to file descriptor *fd*, so that it is at
829 most *length* bytes in size. As of Python 3.3, this is equivalent to 819 most *length* bytes in size. As of Python 3.3, this is equivalent to
830 ``os.truncate(fd, length)``. 820 ``os.truncate(fd, length)``.
831 821
832 Availability: Unix. 822 Availability: Unix, Windows.
833 823
824 .. versionchanged:: 3.5
825 Added support for Windows
826
827 .. function:: get_blocking(fd)
828
829 Get the blocking mode of the file descriptor: ``False`` if the
830 :data:`O_NONBLOCK` flag is set, ``True`` if the flag is cleared.
831
832 See also :func:`set_blocking` and :meth:`socket.socket.setblocking`.
833
834 Availability: Unix.
835
836 .. versionadded:: 3.5
834 837
835 .. function:: isatty(fd) 838 .. function:: isatty(fd)
836 839
837 Return ``True`` if the file descriptor *fd* is open and connected to a 840 Return ``True`` if the file descriptor *fd* is open and connected to a
838 tty(-like) device, else ``False``. 841 tty(-like) device, else ``False``.
839 842
840 843
841 .. function:: lockf(fd, cmd, len) 844 .. function:: lockf(fd, cmd, len)
842 845
843 Apply, test or remove a POSIX lock on an open file descriptor. 846 Apply, test or remove a POSIX lock on an open file descriptor.
(...skipping 20 matching lines...) Expand all
864 867
865 868
866 .. function:: lseek(fd, pos, how) 869 .. function:: lseek(fd, pos, how)
867 870
868 Set the current position of file descriptor *fd* to position *pos*, modified 871 Set the current position of file descriptor *fd* to position *pos*, modified
869 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the 872 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
870 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the 873 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
871 current position; :const:`SEEK_END` or ``2`` to set it relative to the end of 874 current position; :const:`SEEK_END` or ``2`` to set it relative to the end of
872 the file. Return the new cursor position in bytes, starting from the beginnin g. 875 the file. Return the new cursor position in bytes, starting from the beginnin g.
873 876
874 Availability: Unix, Windows.
875
876 877
877 .. data:: SEEK_SET 878 .. data:: SEEK_SET
878 SEEK_CUR 879 SEEK_CUR
879 SEEK_END 880 SEEK_END
880 881
881 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, 882 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
882 respectively. 883 respectively.
883
884 Availability: Unix, Windows.
885 884
886 .. versionadded:: 3.3 885 .. versionadded:: 3.3
887 Some operating systems could support additional values, like 886 Some operating systems could support additional values, like
888 :data:`os.SEEK_HOLE` or :data:`os.SEEK_DATA`. 887 :data:`os.SEEK_HOLE` or :data:`os.SEEK_DATA`.
889 888
890 889
891 .. function:: open(path, flags, mode=0o777, *, dir_fd=None) 890 .. function:: open(path, flags, mode=0o777, *, dir_fd=None)
892 891
893 Open the file *path* and set various flags according to *flags* and possibly 892 Open the file *path* and set various flags according to *flags* and possibly
894 its mode according to *mode*. When computing *mode*, the current umask value 893 its mode according to *mode*. When computing *mode*, the current umask value
895 is first masked out. Return the file descriptor for the newly opened file. 894 is first masked out. Return the file descriptor for the newly opened file.
896 The new file descriptor is :ref:`non-inheritable <fd_inheritance>`. 895 The new file descriptor is :ref:`non-inheritable <fd_inheritance>`.
897 896
898 For a description of the flag and mode values, see the C run-time documentati on; 897 For a description of the flag and mode values, see the C run-time documentati on;
899 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in 898 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
900 the :mod:`os` module. In particular, on Windows adding 899 the :mod:`os` module. In particular, on Windows adding
901 :const:`O_BINARY` is needed to open files in binary mode. 900 :const:`O_BINARY` is needed to open files in binary mode.
902 901
903 This function can support :ref:`paths relative to directory descriptors 902 This function can support :ref:`paths relative to directory descriptors
904 <dir_fd>` with the *dir_fd* parameter. 903 <dir_fd>` with the *dir_fd* parameter.
905 904
906 Availability: Unix, Windows.
907
908 .. versionchanged:: 3.4 905 .. versionchanged:: 3.4
909 The new file descriptor is now non-inheritable. 906 The new file descriptor is now non-inheritable.
910 907
911 .. note:: 908 .. note::
912 909
913 This function is intended for low-level I/O. For normal usage, use the 910 This function is intended for low-level I/O. For normal usage, use the
914 built-in function :func:`open`, which returns a :term:`file object` with 911 built-in function :func:`open`, which returns a :term:`file object` with
915 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To 912 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
916 wrap a file descriptor in a file object, use :func:`fdopen`. 913 wrap a file descriptor in a file object, use :func:`fdopen`.
917 914
918 .. versionadded:: 3.3 915 .. versionadded:: 3.3
919 The *dir_fd* argument. 916 The *dir_fd* argument.
920 917
918 .. versionchanged:: 3.5
919 If the system call is interrupted and the signal handler does not raise an
920 exception, the function now retries the system call instead of raising an
921 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
922
921 The following constants are options for the *flags* parameter to the 923 The following constants are options for the *flags* parameter to the
922 :func:`~os.open` function. They can be combined using the bitwise OR operator 924 :func:`~os.open` function. They can be combined using the bitwise OR operator
923 ``|``. Some of them are not available on all platforms. For descriptions of 925 ``|``. Some of them are not available on all platforms. For descriptions of
924 their availability and use, consult the :manpage:`open(2)` manual page on Unix 926 their availability and use, consult the :manpage:`open(2)` manual page on Unix
925 or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Window s. 927 or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windo ws.
926 928
927 929
928 .. data:: O_RDONLY 930 .. data:: O_RDONLY
929 O_WRONLY 931 O_WRONLY
930 O_RDWR 932 O_RDWR
931 O_APPEND 933 O_APPEND
932 O_CREAT 934 O_CREAT
933 O_EXCL 935 O_EXCL
934 O_TRUNC 936 O_TRUNC
935 937
(...skipping 142 matching lines...) Expand 10 before | Expand all | Expand 10 after
1078 1080
1079 .. versionadded:: 3.3 1081 .. versionadded:: 3.3
1080 1082
1081 1083
1082 .. function:: read(fd, n) 1084 .. function:: read(fd, n)
1083 1085
1084 Read at most *n* bytes from file descriptor *fd*. Return a bytestring contain ing the 1086 Read at most *n* bytes from file descriptor *fd*. Return a bytestring contain ing the
1085 bytes read. If the end of the file referred to by *fd* has been reached, an 1087 bytes read. If the end of the file referred to by *fd* has been reached, an
1086 empty bytes object is returned. 1088 empty bytes object is returned.
1087 1089
1088 Availability: Unix, Windows.
1089
1090 .. note:: 1090 .. note::
1091 1091
1092 This function is intended for low-level I/O and must be applied to a file 1092 This function is intended for low-level I/O and must be applied to a file
1093 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a 1093 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a
1094 "file object" returned by the built-in function :func:`open` or by 1094 "file object" returned by the built-in function :func:`open` or by
1095 :func:`popen` or :func:`fdopen`, or :data:`sys.stdin`, use its 1095 :func:`popen` or :func:`fdopen`, or :data:`sys.stdin`, use its
1096 :meth:`~file.read` or :meth:`~file.readline` methods. 1096 :meth:`~file.read` or :meth:`~file.readline` methods.
1097 1097
1098 .. versionchanged:: 3.5
1099 If the system call is interrupted and the signal handler does not raise an
1100 exception, the function now retries the system call instead of raising an
1101 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1102
1098 1103
1099 .. function:: sendfile(out, in, offset, count) 1104 .. function:: sendfile(out, in, offset, count)
1100 sendfile(out, in, offset, count, [headers], [trailers], flags=0) 1105 sendfile(out, in, offset, count, [headers], [trailers], flags=0)
1101 1106
1102 Copy *count* bytes from file descriptor *in* to file descriptor *out* 1107 Copy *count* bytes from file descriptor *in* to file descriptor *out*
1103 starting at *offset*. 1108 starting at *offset*.
1104 Return the number of bytes sent. When EOF is reached return 0. 1109 Return the number of bytes sent. When EOF is reached return 0.
1105 1110
1106 The first function notation is supported by all platforms that define 1111 The first function notation is supported by all platforms that define
1107 :func:`sendfile`. 1112 :func:`sendfile`.
1108 1113
1109 On Linux, if *offset* is given as ``None``, the bytes are read from the 1114 On Linux, if *offset* is given as ``None``, the bytes are read from the
1110 current position of *in* and the position of *in* is updated. 1115 current position of *in* and the position of *in* is updated.
1111 1116
1112 The second case may be used on Mac OS X and FreeBSD where *headers* and 1117 The second case may be used on Mac OS X and FreeBSD where *headers* and
1113 *trailers* are arbitrary sequences of buffers that are written before and 1118 *trailers* are arbitrary sequences of buffers that are written before and
1114 after the data from *in* is written. It returns the same as the first case. 1119 after the data from *in* is written. It returns the same as the first case.
1115 1120
1116 On Mac OS X and FreeBSD, a value of 0 for *count* specifies to send until 1121 On Mac OS X and FreeBSD, a value of 0 for *count* specifies to send until
1117 the end of *in* is reached. 1122 the end of *in* is reached.
1118 1123
1119 All platforms support sockets as *out* file descriptor, and some platforms 1124 All platforms support sockets as *out* file descriptor, and some platforms
1120 allow other types (e.g. regular file, pipe) as well. 1125 allow other types (e.g. regular file, pipe) as well.
1121 1126
1122 Cross-platform applications should not use *headers*, *trailers* and *flags* 1127 Cross-platform applications should not use *headers*, *trailers* and *flags*
1123 arguments. 1128 arguments.
1124 1129
1125 Availability: Unix. 1130 Availability: Unix.
1126 1131
1127 .. versionadded:: 3.3 1132 .. note::
1133
1134 For a higher-level wrapper of :func:`sendfile`, see
1135 :meth:`socket.socket.sendfile`.
1136
1137 .. versionadded:: 3.3
1138
1139
1140 .. function:: set_blocking(fd, blocking)
1141
1142 Set the blocking mode of the specified file descriptor. Set the
1143 :data:`O_NONBLOCK` flag if blocking is ``False``, clear the flag otherwise.
1144
1145 See also :func:`get_blocking` and :meth:`socket.socket.setblocking`.
1146
1147 Availability: Unix.
1148
1149 .. versionadded:: 3.5
1128 1150
1129 1151
1130 .. data:: SF_NODISKIO 1152 .. data:: SF_NODISKIO
1131 SF_MNOWAIT 1153 SF_MNOWAIT
1132 SF_SYNC 1154 SF_SYNC
1133 1155
1134 Parameters to the :func:`sendfile` function, if the implementation supports 1156 Parameters to the :func:`sendfile` function, if the implementation supports
1135 them. 1157 them.
1136 1158
1137 Availability: Unix. 1159 Availability: Unix.
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
1176 exception is raised. 1198 exception is raised.
1177 1199
1178 Availability: Unix. 1200 Availability: Unix.
1179 1201
1180 1202
1181 .. function:: write(fd, str) 1203 .. function:: write(fd, str)
1182 1204
1183 Write the bytestring in *str* to file descriptor *fd*. Return the number of 1205 Write the bytestring in *str* to file descriptor *fd*. Return the number of
1184 bytes actually written. 1206 bytes actually written.
1185 1207
1186 Availability: Unix, Windows.
1187
1188 .. note:: 1208 .. note::
1189 1209
1190 This function is intended for low-level I/O and must be applied to a file 1210 This function is intended for low-level I/O and must be applied to a file
1191 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "fi le 1211 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "fi le
1192 object" returned by the built-in function :func:`open` or by :func:`popen` or 1212 object" returned by the built-in function :func:`open` or by :func:`popen` or
1193 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its 1213 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
1194 :meth:`~file.write` method. 1214 :meth:`~file.write` method.
1215
1216 .. versionchanged:: 3.5
1217 If the system call is interrupted and the signal handler does not raise an
1218 exception, the function now retries the system call instead of raising an
1219 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1195 1220
1196 1221
1197 .. function:: writev(fd, buffers) 1222 .. function:: writev(fd, buffers)
1198 1223
1199 Write the contents of *buffers* to file descriptor *fd*. *buffers* must be a 1224 Write the contents of *buffers* to file descriptor *fd*. *buffers* must be a
1200 sequence of :term:`bytes-like objects <bytes-like object>`. 1225 sequence of :term:`bytes-like objects <bytes-like object>`.
1201 :func:`~os.writev` writes the contents of each object to the file descriptor 1226 :func:`~os.writev` writes the contents of each object to the file descriptor
1202 and returns the total number of bytes written. 1227 and returns the total number of bytes written.
1203 1228
1204 Availability: Unix. 1229 Availability: Unix.
(...skipping 143 matching lines...) Expand 10 before | Expand all | Expand 10 after
1348 1373
1349 This function can support specifying :ref:`paths relative to directory 1374 This function can support specifying :ref:`paths relative to directory
1350 descriptors <dir_fd>` and :ref:`not following symlinks <follow_symlinks>`. 1375 descriptors <dir_fd>` and :ref:`not following symlinks <follow_symlinks>`.
1351 1376
1352 If *effective_ids* is ``True``, :func:`access` will perform its access 1377 If *effective_ids* is ``True``, :func:`access` will perform its access
1353 checks using the effective uid/gid instead of the real uid/gid. 1378 checks using the effective uid/gid instead of the real uid/gid.
1354 *effective_ids* may not be supported on your platform; you can check whether 1379 *effective_ids* may not be supported on your platform; you can check whether
1355 or not it is available using :data:`os.supports_effective_ids`. If it is 1380 or not it is available using :data:`os.supports_effective_ids`. If it is
1356 unavailable, using it will raise a :exc:`NotImplementedError`. 1381 unavailable, using it will raise a :exc:`NotImplementedError`.
1357 1382
1358 Availability: Unix, Windows.
1359
1360 .. note:: 1383 .. note::
1361 1384
1362 Using :func:`access` to check if a user is authorized to e.g. open a file 1385 Using :func:`access` to check if a user is authorized to e.g. open a file
1363 before actually doing so using :func:`open` creates a security hole, 1386 before actually doing so using :func:`open` creates a security hole,
1364 because the user might exploit the short time interval between checking 1387 because the user might exploit the short time interval between checking
1365 and opening the file to manipulate it. It's preferable to use :term:`EAFP` 1388 and opening the file to manipulate it. It's preferable to use :term:`EAFP`
1366 techniques. For example:: 1389 techniques. For example::
1367 1390
1368 if os.access("myfile", os.R_OK): 1391 if os.access("myfile", os.R_OK):
1369 with open("myfile") as fp: 1392 with open("myfile") as fp:
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
1401 1424
1402 1425
1403 .. function:: chdir(path) 1426 .. function:: chdir(path)
1404 1427
1405 .. index:: single: directory; changing 1428 .. index:: single: directory; changing
1406 1429
1407 Change the current working directory to *path*. 1430 Change the current working directory to *path*.
1408 1431
1409 This function can support :ref:`specifying a file descriptor <path_fd>`. The 1432 This function can support :ref:`specifying a file descriptor <path_fd>`. The
1410 descriptor must refer to an opened directory, not an open file. 1433 descriptor must refer to an opened directory, not an open file.
1411
1412 Availability: Unix, Windows.
1413 1434
1414 .. versionadded:: 3.3 1435 .. versionadded:: 3.3
1415 Added support for specifying *path* as a file descriptor 1436 Added support for specifying *path* as a file descriptor
1416 on some platforms. 1437 on some platforms.
1417 1438
1418 1439
1419 .. function:: chflags(path, flags, *, follow_symlinks=True) 1440 .. function:: chflags(path, flags, *, follow_symlinks=True)
1420 1441
1421 Set the flags of *path* to the numeric *flags*. *flags* may take a combinatio n 1442 Set the flags of *path* to the numeric *flags*. *flags* may take a combinatio n
1422 (bitwise OR) of the following values (as defined in the :mod:`stat` module): 1443 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
1465 * :data:`stat.S_IXGRP` 1486 * :data:`stat.S_IXGRP`
1466 * :data:`stat.S_IRWXO` 1487 * :data:`stat.S_IRWXO`
1467 * :data:`stat.S_IROTH` 1488 * :data:`stat.S_IROTH`
1468 * :data:`stat.S_IWOTH` 1489 * :data:`stat.S_IWOTH`
1469 * :data:`stat.S_IXOTH` 1490 * :data:`stat.S_IXOTH`
1470 1491
1471 This function can support :ref:`specifying a file descriptor <path_fd>`, 1492 This function can support :ref:`specifying a file descriptor <path_fd>`,
1472 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not 1493 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
1473 following symlinks <follow_symlinks>`. 1494 following symlinks <follow_symlinks>`.
1474 1495
1475 Availability: Unix, Windows.
1476
1477 .. note:: 1496 .. note::
1478 1497
1479 Although Windows supports :func:`chmod`, you can only set the file's 1498 Although Windows supports :func:`chmod`, you can only set the file's
1480 read-only flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD`` 1499 read-only flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
1481 constants or a corresponding integer value). All other bits are ignored. 1500 constants or a corresponding integer value). All other bits are ignored.
1482 1501
1483 .. versionadded:: 3.3 1502 .. versionadded:: 3.3
1484 Added support for specifying *path* as an open file descriptor, 1503 Added support for specifying *path* as an open file descriptor,
1485 and the *dir_fd* and *follow_symlinks* arguments. 1504 and the *dir_fd* and *follow_symlinks* arguments.
1486 1505
(...skipping 30 matching lines...) Expand all
1517 descriptor *fd*. The descriptor must refer to an opened directory, not an 1536 descriptor *fd*. The descriptor must refer to an opened directory, not an
1518 open file. As of Python 3.3, this is equivalent to ``os.chdir(fd)``. 1537 open file. As of Python 3.3, this is equivalent to ``os.chdir(fd)``.
1519 1538
1520 Availability: Unix. 1539 Availability: Unix.
1521 1540
1522 1541
1523 .. function:: getcwd() 1542 .. function:: getcwd()
1524 1543
1525 Return a string representing the current working directory. 1544 Return a string representing the current working directory.
1526 1545
1527 Availability: Unix, Windows.
1528
1529 1546
1530 .. function:: getcwdb() 1547 .. function:: getcwdb()
1531 1548
1532 Return a bytestring representing the current working directory. 1549 Return a bytestring representing the current working directory.
1533
1534 Availability: Unix, Windows.
1535 1550
1536 1551
1537 .. function:: lchflags(path, flags) 1552 .. function:: lchflags(path, flags)
1538 1553
1539 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do 1554 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do
1540 not follow symbolic links. As of Python 3.3, this is equivalent to 1555 not follow symbolic links. As of Python 3.3, this is equivalent to
1541 ``os.chflags(path, flags, follow_symlinks=False)``. 1556 ``os.chflags(path, flags, follow_symlinks=False)``.
1542 1557
1543 Availability: Unix. 1558 Availability: Unix.
1544 1559
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
1588 *path* may be either of type ``str`` or of type ``bytes``. If *path* 1603 *path* may be either of type ``str`` or of type ``bytes``. If *path*
1589 is of type ``bytes``, the filenames returned will also be of type ``bytes``; 1604 is of type ``bytes``, the filenames returned will also be of type ``bytes``;
1590 in all other circumstances, they will be of type ``str``. 1605 in all other circumstances, they will be of type ``str``.
1591 1606
1592 This function can also support :ref:`specifying a file descriptor 1607 This function can also support :ref:`specifying a file descriptor
1593 <path_fd>`; the file descriptor must refer to a directory. 1608 <path_fd>`; the file descriptor must refer to a directory.
1594 1609
1595 .. note:: 1610 .. note::
1596 To encode ``str`` filenames to ``bytes``, use :func:`~os.fsencode`. 1611 To encode ``str`` filenames to ``bytes``, use :func:`~os.fsencode`.
1597 1612
1598 Availability: Unix, Windows. 1613 .. seealso::
1614
1615 The :func:`scandir` function returns directory entries along with
1616 file attribute information, giving better performance for many
1617 common use cases.
1599 1618
1600 .. versionchanged:: 3.2 1619 .. versionchanged:: 3.2
1601 The *path* parameter became optional. 1620 The *path* parameter became optional.
1602 1621
1603 .. versionadded:: 3.3 1622 .. versionadded:: 3.3
1604 Added support for specifying an open file descriptor for *path*. 1623 Added support for specifying an open file descriptor for *path*.
1605 1624
1606 1625
1607 .. function:: lstat(path, \*, dir_fd=None) 1626 .. function:: lstat(path, \*, dir_fd=None)
1608 1627
(...skipping 19 matching lines...) Expand all
1628 1647
1629 .. versionchanged:: 3.3 1648 .. versionchanged:: 3.3
1630 Added the *dir_fd* parameter. 1649 Added the *dir_fd* parameter.
1631 1650
1632 1651
1633 .. function:: mkdir(path, mode=0o777, *, dir_fd=None) 1652 .. function:: mkdir(path, mode=0o777, *, dir_fd=None)
1634 1653
1635 Create a directory named *path* with numeric mode *mode*. 1654 Create a directory named *path* with numeric mode *mode*.
1636 1655
1637 On some systems, *mode* is ignored. Where it is used, the current umask 1656 On some systems, *mode* is ignored. Where it is used, the current umask
1638 value is first masked out. If the directory already exists, :exc:`OSError` 1657 value is first masked out. If the directory already exists,
1639 is raised. 1658 :exc:`FileExistsError` is raised.
1640 1659
1641 This function can also support :ref:`paths relative to directory descriptors 1660 This function can also support :ref:`paths relative to directory descriptors
1642 <dir_fd>`. 1661 <dir_fd>`.
1643 1662
1644 It is also possible to create temporary directories; see the 1663 It is also possible to create temporary directories; see the
1645 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function. 1664 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1646
1647 Availability: Unix, Windows.
1648 1665
1649 .. versionadded:: 3.3 1666 .. versionadded:: 3.3
1650 The *dir_fd* argument. 1667 The *dir_fd* argument.
1651 1668
1652 1669
1653 .. function:: makedirs(name, mode=0o777, exist_ok=False) 1670 .. function:: makedirs(name, mode=0o777, exist_ok=False)
1654 1671
1655 .. index:: 1672 .. index::
1656 single: directory; creating 1673 single: directory; creating
1657 single: UNC paths; and os.makedirs() 1674 single: UNC paths; and os.makedirs()
(...skipping 110 matching lines...) Expand 10 before | Expand all | Expand 10 after
1768 1785
1769 1786
1770 .. function:: readlink(path, *, dir_fd=None) 1787 .. function:: readlink(path, *, dir_fd=None)
1771 1788
1772 Return a string representing the path to which the symbolic link points. The 1789 Return a string representing the path to which the symbolic link points. The
1773 result may be either an absolute or relative pathname; if it is relative, it 1790 result may be either an absolute or relative pathname; if it is relative, it
1774 may be converted to an absolute pathname using 1791 may be converted to an absolute pathname using
1775 ``os.path.join(os.path.dirname(path), result)``. 1792 ``os.path.join(os.path.dirname(path), result)``.
1776 1793
1777 If the *path* is a string object, the result will also be a string object, 1794 If the *path* is a string object, the result will also be a string object,
1778 and the call may raise an UnicodeDecodeError. If the *path* is a bytes 1795 and the call may raise a UnicodeDecodeError. If the *path* is a bytes
1779 object, the result will be a bytes object. 1796 object, the result will be a bytes object.
1780 1797
1781 This function can also support :ref:`paths relative to directory descriptors 1798 This function can also support :ref:`paths relative to directory descriptors
1782 <dir_fd>`. 1799 <dir_fd>`.
1783 1800
1784 Availability: Unix, Windows 1801 Availability: Unix, Windows
1785 1802
1786 .. versionchanged:: 3.2 1803 .. versionchanged:: 3.2
1787 Added support for Windows 6.0 (Vista) symbolic links. 1804 Added support for Windows 6.0 (Vista) symbolic links.
1788 1805
1789 .. versionadded:: 3.3 1806 .. versionadded:: 3.3
1790 The *dir_fd* argument. 1807 The *dir_fd* argument.
1791 1808
1792 1809
1793 .. function:: remove(path, *, dir_fd=None) 1810 .. function:: remove(path, *, dir_fd=None)
1794 1811
1795 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is 1812 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
1796 raised. Use :func:`rmdir` to remove directories. 1813 raised. Use :func:`rmdir` to remove directories.
1797 1814
1798 This function can support :ref:`paths relative to directory descriptors 1815 This function can support :ref:`paths relative to directory descriptors
1799 <dir_fd>`. 1816 <dir_fd>`.
1800 1817
1801 On Windows, attempting to remove a file that is in use causes an exception to 1818 On Windows, attempting to remove a file that is in use causes an exception to
1802 be raised; on Unix, the directory entry is removed but the storage allocated 1819 be raised; on Unix, the directory entry is removed but the storage allocated
1803 to the file is not made available until the original file is no longer in use . 1820 to the file is not made available until the original file is no longer in use .
1804 1821
1805 This function is identical to :func:`unlink`. 1822 This function is semantically identical to :func:`unlink`.
1806
1807 Availability: Unix, Windows.
1808 1823
1809 .. versionadded:: 3.3 1824 .. versionadded:: 3.3
1810 The *dir_fd* argument. 1825 The *dir_fd* argument.
1811 1826
1812 1827
1813 .. function:: removedirs(name) 1828 .. function:: removedirs(name)
1814 1829
1815 .. index:: single: directory; deleting 1830 .. index:: single: directory; deleting
1816 1831
1817 Remove directories recursively. Works like :func:`rmdir` except that, if the 1832 Remove directories recursively. Works like :func:`rmdir` except that, if the
(...skipping 14 matching lines...) Expand all
1832 Unix flavors if *src* and *dst* are on different filesystems. If successful, 1847 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1833 the renaming will be an atomic operation (this is a POSIX requirement). On 1848 the renaming will be an atomic operation (this is a POSIX requirement). On
1834 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a 1849 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1835 file. 1850 file.
1836 1851
1837 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to 1852 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
1838 supply :ref:`paths relative to directory descriptors <dir_fd>`. 1853 supply :ref:`paths relative to directory descriptors <dir_fd>`.
1839 1854
1840 If you want cross-platform overwriting of the destination, use :func:`replace `. 1855 If you want cross-platform overwriting of the destination, use :func:`replace `.
1841 1856
1842 Availability: Unix, Windows.
1843
1844 .. versionadded:: 3.3 1857 .. versionadded:: 3.3
1845 The *src_dir_fd* and *dst_dir_fd* arguments. 1858 The *src_dir_fd* and *dst_dir_fd* arguments.
1846 1859
1847 1860
1848 .. function:: renames(old, new) 1861 .. function:: renames(old, new)
1849 1862
1850 Recursive directory or file renaming function. Works like :func:`rename`, exc ept 1863 Recursive directory or file renaming function. Works like :func:`rename`, exc ept
1851 creation of any intermediate directories needed to make the new pathname good is 1864 creation of any intermediate directories needed to make the new pathname good is
1852 attempted first. After the rename, directories corresponding to rightmost pat h 1865 attempted first. After the rename, directories corresponding to rightmost pat h
1853 segments of the old name will be pruned away using :func:`removedirs`. 1866 segments of the old name will be pruned away using :func:`removedirs`.
1854 1867
1855 .. note:: 1868 .. note::
1856 1869
1857 This function can fail with the new directory structure made if you lack 1870 This function can fail with the new directory structure made if you lack
1858 permissions needed to remove the leaf directory or file. 1871 permissions needed to remove the leaf directory or file.
1859 1872
1860 1873
1861 .. function:: replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None) 1874 .. function:: replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
1862 1875
1863 Rename the file or directory *src* to *dst*. If *dst* is a directory, 1876 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1864 :exc:`OSError` will be raised. If *dst* exists and is a file, it will 1877 :exc:`OSError` will be raised. If *dst* exists and is a file, it will
1865 be replaced silently if the user has permission. The operation may fail 1878 be replaced silently if the user has permission. The operation may fail
1866 if *src* and *dst* are on different filesystems. If successful, 1879 if *src* and *dst* are on different filesystems. If successful,
1867 the renaming will be an atomic operation (this is a POSIX requirement). 1880 the renaming will be an atomic operation (this is a POSIX requirement).
1868 1881
1869 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to 1882 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
1870 supply :ref:`paths relative to directory descriptors <dir_fd>`. 1883 supply :ref:`paths relative to directory descriptors <dir_fd>`.
1871 1884
1872 Availability: Unix, Windows.
1873
1874 .. versionadded:: 3.3 1885 .. versionadded:: 3.3
1875 1886
1876 1887
1877 .. function:: rmdir(path, *, dir_fd=None) 1888 .. function:: rmdir(path, *, dir_fd=None)
1878 1889
1879 Remove (delete) the directory *path*. Only works when the directory is 1890 Remove (delete) the directory *path*. Only works when the directory is
1880 empty, otherwise, :exc:`OSError` is raised. In order to remove whole 1891 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
1881 directory trees, :func:`shutil.rmtree` can be used. 1892 directory trees, :func:`shutil.rmtree` can be used.
1882 1893
1883 This function can support :ref:`paths relative to directory descriptors 1894 This function can support :ref:`paths relative to directory descriptors
1884 <dir_fd>`. 1895 <dir_fd>`.
1885 1896
1886 Availability: Unix, Windows.
1887
1888 .. versionadded:: 3.3 1897 .. versionadded:: 3.3
1889 The *dir_fd* parameter. 1898 The *dir_fd* parameter.
1899
1900
1901 .. function:: scandir(path='.')
1902
1903 Return an iterator of :class:`DirEntry` objects corresponding to the entries
1904 in the directory given by *path*. The entries are yielded in arbitrary
1905 order, and the special entries ``'.'`` and ``'..'`` are not included.
1906
1907 Using :func:`scandir` instead of :func:`listdir` can significantly
1908 increase the performance of code that also needs file type or file
1909 attribute information, because :class:`DirEntry` objects expose this
1910 information if the operating system provides it when scanning a directory.
1911 All :class:`DirEntry` methods may perform a system call, but
1912 :func:`~DirEntry.is_dir` and :func:`~DirEntry.is_file` usually only
1913 require a system call for symbolic links; :func:`DirEntry.stat`
1914 always requires a system call on Unix but only requires one for
1915 symbolic links on Windows.
1916
1917 On Unix, *path* can be of type :class:`str` or :class:`bytes` (use
1918 :func:`~os.fsencode` and :func:`~os.fsdecode` to encode and decode
1919 :class:`bytes` paths). On Windows, *path* must be of type :class:`str`.
1920 On both sytems, the type of the :attr:`~DirEntry.name` and
1921 :attr:`~DirEntry.path` attributes of each :class:`DirEntry` will be of
1922 the same type as *path*.
1923
1924 The :func:`scandir` iterator supports the :term:`context manager` protocol
1925 and has the following method:
1926
1927 .. method:: scandir.close()
1928
1929 Close the iterator and free acquired resources.
1930
1931 This is called automatically when the iterator is exhausted or garbage
1932 collected, or when an error happens during iterating. However it
1933 is advisable to call it explicitly or use the :keyword:`with`
1934 statement.
1935
1936 .. versionadded:: 3.6
1937
1938 The following example shows a simple use of :func:`scandir` to display all
1939 the files (excluding directories) in the given *path* that don't start with
1940 ``'.'``. The ``entry.is_file()`` call will generally not make an additional
1941 system call::
1942
1943 with os.scandir(path) as it:
1944 for entry in it:
1945 if not entry.name.startswith('.') and entry.is_file():
1946 print(entry.name)
1947
1948 .. note::
1949
1950 On Unix-based systems, :func:`scandir` uses the system's
1951 `opendir() <http://pubs.opengroup.org/onlinepubs/009695399/functions/opend ir.html>`_
1952 and
1953 `readdir() <http://pubs.opengroup.org/onlinepubs/009695399/functions/readd ir_r.html>`_
1954 functions. On Windows, it uses the Win32
1955 `FindFirstFileW <https://msdn.microsoft.com/en-us/library/windows/desktop/ aa364418(v=vs.85).aspx>`_
1956 and
1957 `FindNextFileW <https://msdn.microsoft.com/en-us/library/windows/desktop/a a364428(v=vs.85).aspx>`_
1958 functions.
1959
1960 .. versionadded:: 3.5
1961
1962 .. versionadded:: 3.6
1963 Added support for the :term:`context manager` protocol and the
1964 :func:`~scandir.close()` method. If a :func:`scandir` iterator is neither
1965 exhausted nor explicitly closed a :exc:`ResourceWarning` will be emitted
1966 in its destructor.
1967
1968
1969 .. class:: DirEntry
1970
1971 Object yielded by :func:`scandir` to expose the file path and other file
1972 attributes of a directory entry.
1973
1974 :func:`scandir` will provide as much of this information as possible without
1975 making additional system calls. When a ``stat()`` or ``lstat()`` system call
1976 is made, the ``DirEntry`` object will cache the result.
1977
1978 ``DirEntry`` instances are not intended to be stored in long-lived data
1979 structures; if you know the file metadata has changed or if a long time has
1980 elapsed since calling :func:`scandir`, call ``os.stat(entry.path)`` to fetch
1981 up-to-date information.
1982
1983 Because the ``DirEntry`` methods can make operating system calls, they may
1984 also raise :exc:`OSError`. If you need very fine-grained
1985 control over errors, you can catch :exc:`OSError` when calling one of the
1986 ``DirEntry`` methods and handle as appropriate.
1987
1988 Attributes and methods on a ``DirEntry`` instance are as follows:
1989
1990 .. attribute:: name
1991
1992 The entry's base filename, relative to the :func:`scandir` *path*
1993 argument.
1994
1995 The :attr:`name` attribute will be of the same type (``str`` or
1996 ``bytes``) as the :func:`scandir` *path* argument. Use
1997 :func:`~os.fsdecode` to decode byte filenames.
1998
1999 .. attribute:: path
2000
2001 The entry's full path name: equivalent to ``os.path.join(scandir_path,
2002 entry.name)`` where *scandir_path* is the :func:`scandir` *path*
2003 argument. The path is only absolute if the :func:`scandir` *path*
2004 argument was absolute.
2005
2006 The :attr:`path` attribute will be of the same type (``str`` or
2007 ``bytes``) as the :func:`scandir` *path* argument. Use
2008 :func:`~os.fsdecode` to decode byte filenames.
2009
2010 .. method:: inode()
2011
2012 Return the inode number of the entry.
2013
2014 The result is cached on the ``DirEntry`` object. Use ``os.stat(entry.path,
2015 follow_symlinks=False).st_ino`` to fetch up-to-date information.
2016
2017 On the first, uncached call, a system call is required on Windows but
2018 not on Unix.
2019
2020 .. method:: is_dir(\*, follow_symlinks=True)
2021
2022 Return ``True`` if this entry is a directory or a symbolic link pointing
2023 to a directory; return ``False`` if the entry is or points to any other
2024 kind of file, or if it doesn't exist anymore.
2025
2026 If *follow_symlinks* is ``False``, return ``True`` only if this entry
2027 is a directory (without following symlinks); return ``False`` if the
2028 entry is any other kind of file or if it doesn't exist anymore.
2029
2030 The result is cached on the ``DirEntry`` object, with a separate cache
2031 for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` along
2032 with :func:`stat.S_ISDIR` to fetch up-to-date information.
2033
2034 On the first, uncached call, no system call is required in most cases.
2035 Specifically, for non-symlinks, neither Windows or Unix require a system
2036 call, except on certain Unix file systems, such as network file systems,
2037 that return ``dirent.d_type == DT_UNKNOWN``. If the entry is a symlink,
2038 a system call will be required to follow the symlink unless
2039 *follow_symlinks* is ``False``.
2040
2041 This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2042 but :exc:`FileNotFoundError` is caught and not raised.
2043
2044 .. method:: is_file(\*, follow_symlinks=True)
2045
2046 Return ``True`` if this entry is a file or a symbolic link pointing to a
2047 file; return ``False`` if the entry is or points to a directory or other
2048 non-file entry, or if it doesn't exist anymore.
2049
2050 If *follow_symlinks* is ``False``, return ``True`` only if this entry
2051 is a file (without following symlinks); return ``False`` if the entry is
2052 a directory or other non-file entry, or if it doesn't exist anymore.
2053
2054 The result is cached on the ``DirEntry`` object. Caching, system calls
2055 made, and exceptions raised are as per :func:`~DirEntry.is_dir`.
2056
2057 .. method:: is_symlink()
2058
2059 Return ``True`` if this entry is a symbolic link (even if broken);
2060 return ``False`` if the entry points to a directory or any kind of file,
2061 or if it doesn't exist anymore.
2062
2063 The result is cached on the ``DirEntry`` object. Call
2064 :func:`os.path.islink` to fetch up-to-date information.
2065
2066 On the first, uncached call, no system call is required in most cases.
2067 Specifically, neither Windows or Unix require a system call, except on
2068 certain Unix file systems, such as network file systems, that return
2069 ``dirent.d_type == DT_UNKNOWN``.
2070
2071 This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2072 but :exc:`FileNotFoundError` is caught and not raised.
2073
2074 .. method:: stat(\*, follow_symlinks=True)
2075
2076 Return a :class:`stat_result` object for this entry. This method
2077 follows symbolic links by default; to stat a symbolic link add the
2078 ``follow_symlinks=False`` argument.
2079
2080 On Unix, this method always requires a system call. On Windows, it
2081 only requires a system call if *follow_symlinks* is ``True`` and the
2082 entry is a symbolic link.
2083
2084 On Windows, the ``st_ino``, ``st_dev`` and ``st_nlink`` attributes of the
2085 :class:`stat_result` are always set to zero. Call :func:`os.stat` to
2086 get these attributes.
2087
2088 The result is cached on the ``DirEntry`` object, with a separate cache
2089 for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` to
2090 fetch up-to-date information.
2091
2092 Note that there is a nice correspondence between several attributes
2093 and methods of ``DirEntry`` and of :class:`pathlib.Path`. In
2094 particular, the ``name`` and ``path`` attributes have the same
2095 meaning, as do the ``is_dir()``, ``is_file()``, ``is_symlink()``
2096 and ``stat()`` methods.
2097
2098 .. versionadded:: 3.5
1890 2099
1891 2100
1892 .. function:: stat(path, \*, dir_fd=None, follow_symlinks=True) 2101 .. function:: stat(path, \*, dir_fd=None, follow_symlinks=True)
1893 2102
1894 Get the status of a file or a file descriptor. Perform the equivalent of a 2103 Get the status of a file or a file descriptor. Perform the equivalent of a
1895 :c:func:`stat` system call on the given path. *path* may be specified as 2104 :c:func:`stat` system call on the given path. *path* may be specified as
1896 either a string or as an open file descriptor. Return a :class:`stat_result` 2105 either a string or as an open file descriptor. Return a :class:`stat_result`
1897 object. 2106 object.
1898 2107
1899 This function normally follows symlinks; to stat a symlink add the argument 2108 This function normally follows symlinks; to stat a symlink add the argument
1900 ``follow_symlinks=False``, or use :func:`lstat`. 2109 ``follow_symlinks=False``, or use :func:`lstat`.
1901 2110
1902 This function can support :ref:`specifying a file descriptor <path_fd>` and 2111 This function can support :ref:`specifying a file descriptor <path_fd>` and
1903 :ref:`not following symlinks <follow_symlinks>`. 2112 :ref:`not following symlinks <follow_symlinks>`.
1904 2113
1905 .. index:: module: stat 2114 .. index:: module: stat
1906 2115
1907 Example:: 2116 Example::
1908 2117
1909 >>> import os 2118 >>> import os
1910 >>> statinfo = os.stat('somefile.txt') 2119 >>> statinfo = os.stat('somefile.txt')
1911 >>> statinfo 2120 >>> statinfo
1912 os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026, 2121 os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
1913 st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295, 2122 st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
1914 st_mtime=1297230027, st_ctime=1297230027) 2123 st_mtime=1297230027, st_ctime=1297230027)
1915 >>> statinfo.st_size 2124 >>> statinfo.st_size
1916 264 2125 264
1917 2126
1918 Availability: Unix, Windows.
1919
1920 .. seealso:: 2127 .. seealso::
1921 2128
1922 :func:`fstat` and :func:`lstat` functions. 2129 :func:`fstat` and :func:`lstat` functions.
1923 2130
1924 .. versionadded:: 3.3 2131 .. versionadded:: 3.3
1925 Added the *dir_fd* and *follow_symlinks* arguments, specifying a file 2132 Added the *dir_fd* and *follow_symlinks* arguments, specifying a file
1926 descriptor instead of a path. 2133 descriptor instead of a path.
1927 2134
1928 2135
1929 .. class:: stat_result 2136 .. class:: stat_result
(...skipping 127 matching lines...) Expand 10 before | Expand all | Expand 10 after
2057 Real size of the file. 2264 Real size of the file.
2058 2265
2059 .. attribute:: st_creator 2266 .. attribute:: st_creator
2060 2267
2061 Creator of the file. 2268 Creator of the file.
2062 2269
2063 .. attribute:: st_type 2270 .. attribute:: st_type
2064 2271
2065 File type. 2272 File type.
2066 2273
2274 On Windows systems, the following attribute is also available:
2275
2276 .. attribute:: st_file_attributes
2277
2278 Windows file attributes: ``dwFileAttributes`` member of the
2279 ``BY_HANDLE_FILE_INFORMATION`` structure returned by
2280 :c:func:`GetFileInformationByHandle`. See the ``FILE_ATTRIBUTE_*``
2281 constants in the :mod:`stat` module.
2282
2067 The standard module :mod:`stat` defines functions and constants that are 2283 The standard module :mod:`stat` defines functions and constants that are
2068 useful for extracting information from a :c:type:`stat` structure. (On 2284 useful for extracting information from a :c:type:`stat` structure. (On
2069 Windows, some items are filled with dummy values.) 2285 Windows, some items are filled with dummy values.)
2070 2286
2071 For backward compatibility, a :class:`stat_result` instance is also 2287 For backward compatibility, a :class:`stat_result` instance is also
2072 accessible as a tuple of at least 10 integers giving the most important (and 2288 accessible as a tuple of at least 10 integers giving the most important (and
2073 portable) members of the :c:type:`stat` structure, in the order 2289 portable) members of the :c:type:`stat` structure, in the order
2074 :attr:`st_mode`, :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, 2290 :attr:`st_mode`, :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`,
2075 :attr:`st_uid`, :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, 2291 :attr:`st_uid`, :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`,
2076 :attr:`st_mtime`, :attr:`st_ctime`. More items may be added at the end by 2292 :attr:`st_mtime`, :attr:`st_ctime`. More items may be added at the end by
2077 some implementations. For compatibility with older Python versions, 2293 some implementations. For compatibility with older Python versions,
2078 accessing :class:`stat_result` as a tuple always returns integers. 2294 accessing :class:`stat_result` as a tuple always returns integers.
2079 2295
2080 .. versionadded:: 3.3 2296 .. versionadded:: 3.3
2081 Added the :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and 2297 Added the :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and
2082 :attr:`st_ctime_ns` members. 2298 :attr:`st_ctime_ns` members.
2083 2299
2300 .. versionadded:: 3.5
2301 Added the :attr:`st_file_attributes` member on Windows.
2302
2084 2303
2085 .. function:: stat_float_times([newvalue]) 2304 .. function:: stat_float_times([newvalue])
2086 2305
2087 Determine whether :class:`stat_result` represents time stamps as float object s. 2306 Determine whether :class:`stat_result` represents time stamps as float object s.
2088 If *newvalue* is ``True``, future calls to :func:`~os.stat` return floats, if it is 2307 If *newvalue* is ``True``, future calls to :func:`~os.stat` return floats, if it is
2089 ``False``, future calls return ints. If *newvalue* is omitted, return the 2308 ``False``, future calls return ints. If *newvalue* is omitted, return the
2090 current setting. 2309 current setting.
2091 2310
2092 For compatibility with older Python versions, accessing :class:`stat_result` as 2311 For compatibility with older Python versions, accessing :class:`stat_result` as
2093 a tuple always returns integers. 2312 a tuple always returns integers.
(...skipping 183 matching lines...) Expand 10 before | Expand all | Expand 10 after
2277 .. versionadded:: 3.3 2496 .. versionadded:: 3.3
2278 2497
2279 2498
2280 .. function:: truncate(path, length) 2499 .. function:: truncate(path, length)
2281 2500
2282 Truncate the file corresponding to *path*, so that it is at most 2501 Truncate the file corresponding to *path*, so that it is at most
2283 *length* bytes in size. 2502 *length* bytes in size.
2284 2503
2285 This function can support :ref:`specifying a file descriptor <path_fd>`. 2504 This function can support :ref:`specifying a file descriptor <path_fd>`.
2286 2505
2287 Availability: Unix. 2506 Availability: Unix, Windows.
2288 2507
2289 .. versionadded:: 3.3 2508 .. versionadded:: 3.3
2290 2509
2510 .. versionchanged:: 3.5
2511 Added support for Windows
2291 2512
2292 .. function:: unlink(path, *, dir_fd=None) 2513 .. function:: unlink(path, *, dir_fd=None)
2293 2514
2294 Remove (delete) the file *path*. This function is identical to 2515 Remove (delete) the file *path*. This function is semantically
2295 :func:`remove`; the ``unlink`` name is its traditional Unix 2516 identical to :func:`remove`; the ``unlink`` name is its
2296 name. Please see the documentation for :func:`remove` for 2517 traditional Unix name. Please see the documentation for
2297 further information. 2518 :func:`remove` for further information.
2298
2299 Availability: Unix, Windows.
2300 2519
2301 .. versionadded:: 3.3 2520 .. versionadded:: 3.3
2302 The *dir_fd* parameter. 2521 The *dir_fd* parameter.
2303 2522
2304 2523
2305 .. function:: utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True ) 2524 .. function:: utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True )
2306 2525
2307 Set the access and modified times of the file specified by *path*. 2526 Set the access and modified times of the file specified by *path*.
2308 2527
2309 :func:`utime` takes two optional parameters, *times* and *ns*. 2528 :func:`utime` takes two optional parameters, *times* and *ns*.
(...skipping 16 matching lines...) Expand all
2326 (for example, Windows does not). Note that the exact times you set here may 2545 (for example, Windows does not). Note that the exact times you set here may
2327 not be returned by a subsequent :func:`~os.stat` call, depending on the 2546 not be returned by a subsequent :func:`~os.stat` call, depending on the
2328 resolution with which your operating system records access and modification 2547 resolution with which your operating system records access and modification
2329 times; see :func:`~os.stat`. The best way to preserve exact times is to 2548 times; see :func:`~os.stat`. The best way to preserve exact times is to
2330 use the *st_atime_ns* and *st_mtime_ns* fields from the :func:`os.stat` 2549 use the *st_atime_ns* and *st_mtime_ns* fields from the :func:`os.stat`
2331 result object with the *ns* parameter to `utime`. 2550 result object with the *ns* parameter to `utime`.
2332 2551
2333 This function can support :ref:`specifying a file descriptor <path_fd>`, 2552 This function can support :ref:`specifying a file descriptor <path_fd>`,
2334 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not 2553 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
2335 following symlinks <follow_symlinks>`. 2554 following symlinks <follow_symlinks>`.
2336
2337 Availability: Unix, Windows.
2338 2555
2339 .. versionadded:: 3.3 2556 .. versionadded:: 3.3
2340 Added support for specifying an open file descriptor for *path*, 2557 Added support for specifying an open file descriptor for *path*,
2341 and the *dir_fd*, *follow_symlinks*, and *ns* parameters. 2558 and the *dir_fd*, *follow_symlinks*, and *ns* parameters.
2342 2559
2343 2560
2344 .. function:: walk(top, topdown=True, onerror=None, followlinks=False) 2561 .. function:: walk(top, topdown=True, onerror=None, followlinks=False)
2345 2562
2346 .. index:: 2563 .. index::
2347 single: directory; walking 2564 single: directory; walking
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
2419 # assuming there are no symbolic links. 2636 # assuming there are no symbolic links.
2420 # CAUTION: This is dangerous! For example, if top == '/', it 2637 # CAUTION: This is dangerous! For example, if top == '/', it
2421 # could delete all your disk files. 2638 # could delete all your disk files.
2422 import os 2639 import os
2423 for root, dirs, files in os.walk(top, topdown=False): 2640 for root, dirs, files in os.walk(top, topdown=False):
2424 for name in files: 2641 for name in files:
2425 os.remove(os.path.join(root, name)) 2642 os.remove(os.path.join(root, name))
2426 for name in dirs: 2643 for name in dirs:
2427 os.rmdir(os.path.join(root, name)) 2644 os.rmdir(os.path.join(root, name))
2428 2645
2646 .. versionchanged:: 3.5
2647 This function now calls :func:`os.scandir` instead of :func:`os.listdir`,
2648 making it faster by reducing the number of calls to :func:`os.stat`.
2649
2429 2650
2430 .. function:: fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=Fals e, dir_fd=None) 2651 .. function:: fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=Fals e, dir_fd=None)
2431 2652
2432 .. index:: 2653 .. index::
2433 single: directory; walking 2654 single: directory; walking
2434 single: directory; traversal 2655 single: directory; traversal
2435 2656
2436 This behaves exactly like :func:`walk`, except that it yields a 4-tuple 2657 This behaves exactly like :func:`walk`, except that it yields a 4-tuple
2437 ``(dirpath, dirnames, filenames, dirfd)``, and it supports ``dir_fd``. 2658 ``(dirpath, dirnames, filenames, dirfd)``, and it supports ``dir_fd``.
2438 2659
(...skipping 136 matching lines...) Expand 10 before | Expand all | Expand 10 after
2575 2796
2576 2797
2577 .. function:: abort() 2798 .. function:: abort()
2578 2799
2579 Generate a :const:`SIGABRT` signal to the current process. On Unix, the defa ult 2800 Generate a :const:`SIGABRT` signal to the current process. On Unix, the defa ult
2580 behavior is to produce a core dump; on Windows, the process immediately retur ns 2801 behavior is to produce a core dump; on Windows, the process immediately retur ns
2581 an exit code of ``3``. Be aware that calling this function will not call the 2802 an exit code of ``3``. Be aware that calling this function will not call the
2582 Python signal handler registered for :const:`SIGABRT` with 2803 Python signal handler registered for :const:`SIGABRT` with
2583 :func:`signal.signal`. 2804 :func:`signal.signal`.
2584 2805
2585 Availability: Unix, Windows.
2586
2587 2806
2588 .. function:: execl(path, arg0, arg1, ...) 2807 .. function:: execl(path, arg0, arg1, ...)
2589 execle(path, arg0, arg1, ..., env) 2808 execle(path, arg0, arg1, ..., env)
2590 execlp(file, arg0, arg1, ...) 2809 execlp(file, arg0, arg1, ...)
2591 execlpe(file, arg0, arg1, ..., env) 2810 execlpe(file, arg0, arg1, ..., env)
2592 execv(path, args) 2811 execv(path, args)
2593 execve(path, args, env) 2812 execve(path, args, env)
2594 execvp(file, args) 2813 execvp(file, args)
2595 execvpe(file, args, env) 2814 execvpe(file, args, env)
2596 2815
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
2640 2859
2641 .. versionadded:: 3.3 2860 .. versionadded:: 3.3
2642 Added support for specifying an open file descriptor for *path* 2861 Added support for specifying an open file descriptor for *path*
2643 for :func:`execve`. 2862 for :func:`execve`.
2644 2863
2645 .. function:: _exit(n) 2864 .. function:: _exit(n)
2646 2865
2647 Exit the process with status *n*, without calling cleanup handlers, flushing 2866 Exit the process with status *n*, without calling cleanup handlers, flushing
2648 stdio buffers, etc. 2867 stdio buffers, etc.
2649 2868
2650 Availability: Unix, Windows.
2651
2652 .. note:: 2869 .. note::
2653 2870
2654 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should 2871 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should
2655 normally only be used in the child process after a :func:`fork`. 2872 normally only be used in the child process after a :func:`fork`.
2656 2873
2657 The following exit codes are defined and can be used with :func:`_exit`, 2874 The following exit codes are defined and can be used with :func:`_exit`,
2658 although they are not required. These are typically used for system programs 2875 although they are not required. These are typically used for system programs
2659 written in Python, such as a mail server's external command delivery program. 2876 written in Python, such as a mail server's external command delivery program.
2660 2877
2661 .. note:: 2878 .. note::
(...skipping 341 matching lines...) Expand 10 before | Expand all | Expand 10 after
3003 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` an d 3220 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` an d
3004 ``'find'`` (to be used on directories). 3221 ``'find'`` (to be used on directories).
3005 3222
3006 :func:`startfile` returns as soon as the associated application is launched. 3223 :func:`startfile` returns as soon as the associated application is launched.
3007 There is no option to wait for the application to close, and no way to retrie ve 3224 There is no option to wait for the application to close, and no way to retrie ve
3008 the application's exit status. The *path* parameter is relative to the curre nt 3225 the application's exit status. The *path* parameter is relative to the curre nt
3009 directory. If you want to use an absolute path, make sure the first characte r 3226 directory. If you want to use an absolute path, make sure the first characte r
3010 is not a slash (``'/'``); the underlying Win32 :c:func:`ShellExecute` functio n 3227 is not a slash (``'/'``); the underlying Win32 :c:func:`ShellExecute` functio n
3011 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure t hat 3228 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure t hat
3012 the path is properly encoded for Win32. 3229 the path is properly encoded for Win32.
3230
3231 To reduce interpreter startup overhead, the Win32 :c:func:`ShellExecute`
3232 function is not resolved until this function is first called. If the functio n
3233 cannot be resolved, :exc:`NotImplementedError` will be raised.
3013 3234
3014 Availability: Windows. 3235 Availability: Windows.
3015 3236
3016 3237
3017 .. function:: system(command) 3238 .. function:: system(command)
3018 3239
3019 Execute the command (a string) in a subshell. This is implemented by calling 3240 Execute the command (a string) in a subshell. This is implemented by calling
3020 the Standard C function :c:func:`system`, and has the same limitations. 3241 the Standard C function :c:func:`system`, and has the same limitations.
3021 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of 3242 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of
3022 the executed command. If *command* generates any output, it will be sent to 3243 the executed command. If *command* generates any output, it will be sent to
(...skipping 128 matching lines...) Expand 10 before | Expand all | Expand 10 after
3151 returns -1. 3372 returns -1.
3152 3373
3153 On Windows: Wait for completion of a process given by process handle *pid*, a nd 3374 On Windows: Wait for completion of a process given by process handle *pid*, a nd
3154 return a tuple containing *pid*, and its exit status shifted left by 8 bits 3375 return a tuple containing *pid*, and its exit status shifted left by 8 bits
3155 (shifting makes cross-platform use of the function easier). A *pid* less than or 3376 (shifting makes cross-platform use of the function easier). A *pid* less than or
3156 equal to ``0`` has no special meaning on Windows, and raises an exception. Th e 3377 equal to ``0`` has no special meaning on Windows, and raises an exception. Th e
3157 value of integer *options* has no effect. *pid* can refer to any process whos e 3378 value of integer *options* has no effect. *pid* can refer to any process whos e
3158 id is known, not necessarily a child process. The :func:`spawn\* <spawnl>` 3379 id is known, not necessarily a child process. The :func:`spawn\* <spawnl>`
3159 functions called with :const:`P_NOWAIT` return suitable process handles. 3380 functions called with :const:`P_NOWAIT` return suitable process handles.
3160 3381
3382 .. versionchanged:: 3.5
3383 If the system call is interrupted and the signal handler does not raise an
3384 exception, the function now retries the system call instead of raising an
3385 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
3386
3161 3387
3162 .. function:: wait3(options) 3388 .. function:: wait3(options)
3163 3389
3164 Similar to :func:`waitpid`, except no process id argument is given and a 3390 Similar to :func:`waitpid`, except no process id argument is given and a
3165 3-element tuple containing the child's process id, exit status indication, an d 3391 3-element tuple containing the child's process id, exit status indication, an d
3166 resource usage information is returned. Refer to :mod:`resource`.\ 3392 resource usage information is returned. Refer to :mod:`resource`.\
3167 :func:`~resource.getrusage` for details on resource usage information. The 3393 :func:`~resource.getrusage` for details on resource usage information. The
3168 option argument is the same as that provided to :func:`waitpid` and 3394 option argument is the same as that provided to :func:`waitpid` and
3169 :func:`wait4`. 3395 :func:`wait4`.
3170 3396
(...skipping 133 matching lines...) Expand 10 before | Expand all | Expand 10 after
3304 .. data:: SCHED_FIFO 3530 .. data:: SCHED_FIFO
3305 3531
3306 A First In First Out scheduling policy. 3532 A First In First Out scheduling policy.
3307 3533
3308 .. data:: SCHED_RR 3534 .. data:: SCHED_RR
3309 3535
3310 A round-robin scheduling policy. 3536 A round-robin scheduling policy.
3311 3537
3312 .. data:: SCHED_RESET_ON_FORK 3538 .. data:: SCHED_RESET_ON_FORK
3313 3539
3314 This flag can OR'ed with any other scheduling policy. When a process with 3540 This flag can be OR'ed with any other scheduling policy. When a process with
3315 this flag set forks, its child's scheduling policy and priority are reset to 3541 this flag set forks, its child's scheduling policy and priority are reset to
3316 the default. 3542 the default.
3317 3543
3318 3544
3319 .. class:: sched_param(sched_priority) 3545 .. class:: sched_param(sched_priority)
3320 3546
3321 This class represents tunable scheduling parameters used in 3547 This class represents tunable scheduling parameters used in
3322 :func:`sched_setparam`, :func:`sched_setscheduler`, and 3548 :func:`sched_setparam`, :func:`sched_setscheduler`, and
3323 :func:`sched_getparam`. It is immutable. 3549 :func:`sched_getparam`. It is immutable.
3324 3550
(...skipping 99 matching lines...) Expand 10 before | Expand all | Expand 10 after
3424 defined for those names by the host operating system. This can be used to 3650 defined for those names by the host operating system. This can be used to
3425 determine the set of names known to the system. 3651 determine the set of names known to the system.
3426 3652
3427 Availability: Unix. 3653 Availability: Unix.
3428 3654
3429 3655
3430 .. function:: cpu_count() 3656 .. function:: cpu_count()
3431 3657
3432 Return the number of CPUs in the system. Returns None if undetermined. 3658 Return the number of CPUs in the system. Returns None if undetermined.
3433 3659
3660 This number is not equivalent to the number of CPUs the current process can
3661 use. The number of usable CPUs can be obtained with
3662 ``len(os.sched_getaffinity(0))``
3663
3664
3434 .. versionadded:: 3.4 3665 .. versionadded:: 3.4
3435 3666
3436 3667
3437 .. function:: getloadavg() 3668 .. function:: getloadavg()
3438 3669
3439 Return the number of processes in the system run queue averaged over the last 3670 Return the number of processes in the system run queue averaged over the last
3440 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was 3671 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
3441 unobtainable. 3672 unobtainable.
3442 3673
3443 Availability: Unix. 3674 Availability: Unix.
(...skipping 107 matching lines...) Expand 10 before | Expand all | Expand 10 after
3551 Miscellaneous Functions 3782 Miscellaneous Functions
3552 ----------------------- 3783 -----------------------
3553 3784
3554 3785
3555 .. function:: urandom(n) 3786 .. function:: urandom(n)
3556 3787
3557 Return a string of *n* random bytes suitable for cryptographic use. 3788 Return a string of *n* random bytes suitable for cryptographic use.
3558 3789
3559 This function returns random bytes from an OS-specific randomness source. Th e 3790 This function returns random bytes from an OS-specific randomness source. Th e
3560 returned data should be unpredictable enough for cryptographic applications, 3791 returned data should be unpredictable enough for cryptographic applications,
3561 though its exact quality depends on the OS implementation. On a Unix-like 3792 though its exact quality depends on the OS implementation.
3562 system this will query ``/dev/urandom``, and on Windows it will use 3793
3563 ``CryptGenRandom()``. If a randomness source is not found, 3794 On Linux, ``getrandom()`` syscall is used if available and the urandom
3795 entropy pool is initialized (``getrandom()`` does not block).
3796 On a Unix-like system this will query ``/dev/urandom``. On Windows, it
3797 will use ``CryptGenRandom()``. If a randomness source is not found,
3564 :exc:`NotImplementedError` will be raised. 3798 :exc:`NotImplementedError` will be raised.
3565 3799
3566 For an easy-to-use interface to the random number generator 3800 For an easy-to-use interface to the random number generator
3567 provided by your platform, please see :class:`random.SystemRandom`. 3801 provided by your platform, please see :class:`random.SystemRandom`.
3802
3803 .. versionchanged:: 3.5.2
3804 On Linux, if ``getrandom()`` blocks (the urandom entropy pool is not
3805 initialized yet), fall back on reading ``/dev/urandom``.
3806
3807 .. versionchanged:: 3.5
3808 On Linux 3.17 and newer, the ``getrandom()`` syscall is now used
3809 when available. On OpenBSD 5.6 and newer, the C ``getentropy()``
3810 function is now used. These functions avoid the usage of an internal file
3811 descriptor.
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+