blob: f9f35b3124360da8f943f6b4a9001b1f14bcd3ed [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`os` --- Miscellaneous operating system interfaces
2=======================================================
3
4.. module:: os
5 :synopsis: Miscellaneous operating system interfaces.
6
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007**Source code:** :source:`Lib/os.py`
8
9--------------
Georg Brandl116aa622007-08-15 14:28:22 +000010
Christian Heimesa62da1d2008-01-12 19:39:10 +000011This 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.
Georg Brandl116aa622007-08-15 14:28:22 +000018
Benjamin Peterson1baf4652009-12-31 03:11:23 +000019Notes on the availability of these functions:
Georg Brandl116aa622007-08-15 14:28:22 +000020
Benjamin Peterson1baf4652009-12-31 03:11:23 +000021* 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).
Georg Brandl116aa622007-08-15 14:28:22 +000026
Benjamin Peterson1baf4652009-12-31 03:11:23 +000027* 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.
Georg Brandl116aa622007-08-15 14:28:22 +000030
Benjamin Peterson1baf4652009-12-31 03:11:23 +000031* 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.
Georg Brandl76e55382008-10-08 16:34:57 +000034
pxinwrf2d7ac72019-05-21 18:46:37 +080035* On VxWorks, os.fork, os.execv and os.spawn*p* are not supported.
Benjamin Petersonf650e462010-05-06 23:03:05 +000036
Georg Brandlc575c902008-09-13 17:46:05 +000037.. note::
38
Tim Hoffmanna55f75a2019-07-05 10:41:35 +020039 All functions in this module raise :exc:`OSError` (or subclasses thereof) in
40 the case of invalid or inaccessible file names and paths, or other arguments
41 that have the correct type, but are not accepted by the operating system.
Georg Brandl116aa622007-08-15 14:28:22 +000042
Georg Brandl116aa622007-08-15 14:28:22 +000043.. exception:: error
44
Christian Heimesa62da1d2008-01-12 19:39:10 +000045 An alias for the built-in :exc:`OSError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47
48.. data:: name
49
Benjamin Peterson1baf4652009-12-31 03:11:23 +000050 The name of the operating system dependent module imported. The following
Ned Deily5c867012014-06-26 23:40:06 -070051 names have currently been registered: ``'posix'``, ``'nt'``,
Larry Hastings10108a72016-09-05 15:11:23 -070052 ``'java'``.
Georg Brandl116aa622007-08-15 14:28:22 +000053
Antoine Pitroua83cdaa2011-07-09 15:54:23 +020054 .. seealso::
55 :attr:`sys.platform` has a finer granularity. :func:`os.uname` gives
56 system-dependent version information.
57
58 The :mod:`platform` module provides detailed checks for the
59 system's identity.
60
Georg Brandl116aa622007-08-15 14:28:22 +000061
Martin v. Löwis011e8422009-05-05 04:43:17 +000062.. _os-filenames:
Victor Stinner6bfd8542014-06-19 12:50:27 +020063.. _filesystem-encoding:
Martin v. Löwis011e8422009-05-05 04:43:17 +000064
65File Names, Command Line Arguments, and Environment Variables
66-------------------------------------------------------------
67
Georg Brandl67b21b72010-08-17 15:07:14 +000068In Python, file names, command line arguments, and environment variables are
69represented using the string type. On some systems, decoding these strings to
70and from bytes is necessary before passing them to the operating system. Python
Victor Stinner4b9aad42020-11-02 16:49:54 +010071uses the :term:`filesystem encoding and error handler` to perform this
72conversion (see :func:`sys.getfilesystemencoding`).
73
74The :term:`filesystem encoding and error handler` are configured at Python
75startup by the :c:func:`PyConfig_Read` function: see
76:c:member:`~PyConfig.filesystem_encoding` and
77:c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`.
Martin v. Löwis011e8422009-05-05 04:43:17 +000078
79.. versionchanged:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +000080 On some systems, conversion using the file system encoding may fail. In this
Victor Stinnerf6a271a2014-08-01 12:28:48 +020081 case, Python uses the :ref:`surrogateescape encoding error handler
82 <surrogateescape>`, which means that undecodable bytes are replaced by a
83 Unicode character U+DCxx on decoding, and these are again translated to the
84 original byte on encoding.
Martin v. Löwis011e8422009-05-05 04:43:17 +000085
86
Victor Stinner4b9aad42020-11-02 16:49:54 +010087The :term:`file system encoding <filesystem encoding and error handler>` must
88guarantee to successfully decode all bytes below 128. If the file system
89encoding fails to provide this guarantee, API functions can raise
90:exc:`UnicodeError`.
91
92See also the :term:`locale encoding`.
93
94
95.. _utf8-mode:
96
97Python UTF-8 Mode
98-----------------
99
100.. versionadded:: 3.7
101 See :pep:`540` for more details.
102
103The Python UTF-8 Mode ignores the :term:`locale encoding` and forces the usage
104of the UTF-8 encoding:
105
106* Use UTF-8 as the :term:`filesystem encoding <filesystem encoding and error
107 handler>`.
108* :func:`sys.getfilesystemencoding()` returns ``'UTF-8'``.
109* :func:`locale.getpreferredencoding()` returns ``'UTF-8'`` (the *do_setlocale*
110 argument has no effect).
111* :data:`sys.stdin`, :data:`sys.stdout`, and :data:`sys.stderr` all use
112 UTF-8 as their text encoding, with the ``surrogateescape``
113 :ref:`error handler <error-handlers>` being enabled for :data:`sys.stdin`
114 and :data:`sys.stdout` (:data:`sys.stderr` continues to use
115 ``backslashreplace`` as it does in the default locale-aware mode)
116
117Note that the standard stream settings in UTF-8 mode can be overridden by
118:envvar:`PYTHONIOENCODING` (just as they can be in the default locale-aware
119mode).
120
121As a consequence of the changes in those lower level APIs, other higher
122level APIs also exhibit different default behaviours:
123
124* Command line arguments, environment variables and filenames are decoded
125 to text using the UTF-8 encoding.
126* :func:`os.fsdecode()` and :func:`os.fsencode()` use the UTF-8 encoding.
127* :func:`open()`, :func:`io.open()`, and :func:`codecs.open()` use the UTF-8
128 encoding by default. However, they still use the strict error handler by
129 default so that attempting to open a binary file in text mode is likely
130 to raise an exception rather than producing nonsense data.
131
132The :ref:`Python UTF-8 Mode <utf8-mode>` is enabled if the LC_CTYPE locale is
133``C`` or ``POSIX`` at Python startup (see the :c:func:`PyConfig_Read`
134function).
135
136It can be enabled or disabled using the :option:`-X utf8 <-X>` command line
137option and the :envvar:`PYTHONUTF8` environment variable.
138
139If the :envvar:`PYTHONUTF8` environment variable is not set at all, then the
140interpreter defaults to using the current locale settings, *unless* the current
141locale is identified as a legacy ASCII-based locale (as described for
142:envvar:`PYTHONCOERCECLOCALE`), and locale coercion is either disabled or
143fails. In such legacy locales, the interpreter will default to enabling UTF-8
144mode unless explicitly instructed not to do so.
145
146The Python UTF-8 Mode can only be enabled at the Python startup. Its value
147can be read from :data:`sys.flags.utf8_mode <sys.flags>`.
148
149See also the :ref:`UTF-8 mode on Windows <win-utf8-mode>`
150and the :term:`filesystem encoding and error handler`.
Martin v. Löwis011e8422009-05-05 04:43:17 +0000151
152
Georg Brandl116aa622007-08-15 14:28:22 +0000153.. _os-procinfo:
154
155Process Parameters
156------------------
157
158These functions and data items provide information and operate on the current
159process and user.
160
161
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200162.. function:: ctermid()
163
164 Return the filename corresponding to the controlling terminal of the process.
165
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400166 .. availability:: Unix.
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200167
168
Georg Brandl116aa622007-08-15 14:28:22 +0000169.. data:: environ
170
Chris Jerdonek11f3f172012-11-03 12:05:55 -0700171 A :term:`mapping` object representing the string environment. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000172 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
173 and is equivalent to ``getenv("HOME")`` in C.
174
175 This mapping is captured the first time the :mod:`os` module is imported,
176 typically during Python startup as part of processing :file:`site.py`. Changes
177 to the environment made after this time are not reflected in ``os.environ``,
178 except for changes made by modifying ``os.environ`` directly.
179
Victor Stinnerb8d12622020-01-24 14:05:48 +0100180 This mapping may be used to modify the environment as well as query the
181 environment. :func:`putenv` will be called automatically when the mapping
182 is modified.
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Victor Stinner84ae1182010-05-06 22:05:07 +0000184 On Unix, keys and values use :func:`sys.getfilesystemencoding` and
185 ``'surrogateescape'`` error handler. Use :data:`environb` if you would like
186 to use a different encoding.
187
Georg Brandl116aa622007-08-15 14:28:22 +0000188 .. note::
189
190 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
191 to modify ``os.environ``.
192
193 .. note::
194
Georg Brandlc575c902008-09-13 17:46:05 +0000195 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
196 cause memory leaks. Refer to the system documentation for
Georg Brandl60203b42010-10-06 10:11:56 +0000197 :c:func:`putenv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Victor Stinnerb8d12622020-01-24 14:05:48 +0100199 You can delete items in this mapping to unset environment variables.
200 :func:`unsetenv` will be called automatically when an item is deleted from
201 ``os.environ``, and when one of the :meth:`pop` or :meth:`clear` methods is
202 called.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000203
Charles Burklandd648ef12020-03-13 09:04:43 -0700204 .. versionchanged:: 3.9
205 Updated to support :pep:`584`'s merge (``|``) and update (``|=``) operators.
206
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Victor Stinner84ae1182010-05-06 22:05:07 +0000208.. data:: environb
209
Chris Jerdonek11f3f172012-11-03 12:05:55 -0700210 Bytes version of :data:`environ`: a :term:`mapping` object representing the
Victor Stinner84ae1182010-05-06 22:05:07 +0000211 environment as byte strings. :data:`environ` and :data:`environb` are
212 synchronized (modify :data:`environb` updates :data:`environ`, and vice
213 versa).
214
Victor Stinnerb745a742010-05-18 17:17:23 +0000215 :data:`environb` is only available if :data:`supports_bytes_environ` is
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200216 ``True``.
Victor Stinner84ae1182010-05-06 22:05:07 +0000217
Benjamin Peterson662c74f2010-05-06 22:09:03 +0000218 .. versionadded:: 3.2
219
Charles Burklandd648ef12020-03-13 09:04:43 -0700220 .. versionchanged:: 3.9
221 Updated to support :pep:`584`'s merge (``|``) and update (``|=``) operators.
222
Victor Stinner84ae1182010-05-06 22:05:07 +0000223
Georg Brandl116aa622007-08-15 14:28:22 +0000224.. function:: chdir(path)
225 fchdir(fd)
226 getcwd()
227 :noindex:
228
229 These functions are described in :ref:`os-file-dir`.
230
231
Victor Stinnere8d51452010-08-19 01:05:19 +0000232.. function:: fsencode(filename)
Victor Stinner449c4662010-05-08 11:10:09 +0000233
Victor Stinner4b9aad42020-11-02 16:49:54 +0100234 Encode :term:`path-like <path-like object>` *filename* to the
235 :term:`filesystem encoding and error handler`; return :class:`bytes`
236 unchanged.
Victor Stinnere8d51452010-08-19 01:05:19 +0000237
Antoine Pitroua305ca72010-09-25 22:12:00 +0000238 :func:`fsdecode` is the reverse function.
Victor Stinnere8d51452010-08-19 01:05:19 +0000239
240 .. versionadded:: 3.2
241
Brett Cannonb08388d2016-06-09 15:58:06 -0700242 .. versionchanged:: 3.6
Brett Cannonc78ca1e2016-06-24 12:03:43 -0700243 Support added to accept objects implementing the :class:`os.PathLike`
244 interface.
Brett Cannonb08388d2016-06-09 15:58:06 -0700245
Victor Stinnere8d51452010-08-19 01:05:19 +0000246
247.. function:: fsdecode(filename)
248
Brett Cannonc28592b2016-06-24 12:21:47 -0700249 Decode the :term:`path-like <path-like object>` *filename* from the
Victor Stinner4b9aad42020-11-02 16:49:54 +0100250 :term:`filesystem encoding and error handler`; return :class:`str`
251 unchanged.
Victor Stinnere8d51452010-08-19 01:05:19 +0000252
253 :func:`fsencode` is the reverse function.
Victor Stinner449c4662010-05-08 11:10:09 +0000254
255 .. versionadded:: 3.2
256
Brett Cannonb08388d2016-06-09 15:58:06 -0700257 .. versionchanged:: 3.6
Brett Cannonc78ca1e2016-06-24 12:03:43 -0700258 Support added to accept objects implementing the :class:`os.PathLike`
259 interface.
Brett Cannonb08388d2016-06-09 15:58:06 -0700260
Victor Stinner449c4662010-05-08 11:10:09 +0000261
Ethan Furmancdc08792016-06-02 15:06:09 -0700262.. function:: fspath(path)
263
Brett Cannon0fa1aa12016-06-09 14:37:06 -0700264 Return the file system representation of the path.
Ethan Furmancdc08792016-06-02 15:06:09 -0700265
Brett Cannonc78ca1e2016-06-24 12:03:43 -0700266 If :class:`str` or :class:`bytes` is passed in, it is returned unchanged.
267 Otherwise :meth:`~os.PathLike.__fspath__` is called and its value is
268 returned as long as it is a :class:`str` or :class:`bytes` object.
269 In all other cases, :exc:`TypeError` is raised.
Ethan Furmancdc08792016-06-02 15:06:09 -0700270
Brett Cannonb08388d2016-06-09 15:58:06 -0700271 .. versionadded:: 3.6
272
273
274.. class:: PathLike
275
276 An :term:`abstract base class` for objects representing a file system path,
277 e.g. :class:`pathlib.PurePath`.
278
Berker Peksagb18ffb42016-06-10 08:43:54 +0300279 .. versionadded:: 3.6
280
Brett Cannonb08388d2016-06-09 15:58:06 -0700281 .. abstractmethod:: __fspath__()
282
283 Return the file system path representation of the object.
284
285 The method should only return a :class:`str` or :class:`bytes` object,
286 with the preference being for :class:`str`.
287
Ethan Furmancdc08792016-06-02 15:06:09 -0700288
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200289.. function:: getenv(key, default=None)
290
291 Return the value of the environment variable *key* if it exists, or
292 *default* if it doesn't. *key*, *default* and the result are str.
293
294 On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding`
295 and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you
296 would like to use a different encoding.
297
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400298 .. availability:: most flavors of Unix, Windows.
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200299
300
301.. function:: getenvb(key, default=None)
302
303 Return the value of the environment variable *key* if it exists, or
304 *default* if it doesn't. *key*, *default* and the result are bytes.
305
Berker Peksag996e5f92016-09-26 22:44:07 +0300306 :func:`getenvb` is only available if :data:`supports_bytes_environ`
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200307 is ``True``.
Berker Peksag996e5f92016-09-26 22:44:07 +0300308
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400309 .. availability:: most flavors of Unix.
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200310
311 .. versionadded:: 3.2
312
313
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000314.. function:: get_exec_path(env=None)
315
316 Returns the list of directories that will be searched for a named
317 executable, similar to a shell, when launching a process.
318 *env*, when specified, should be an environment variable dictionary
319 to lookup the PATH in.
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300320 By default, when *env* is ``None``, :data:`environ` is used.
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000321
322 .. versionadded:: 3.2
323
324
Georg Brandl116aa622007-08-15 14:28:22 +0000325.. function:: getegid()
326
327 Return the effective group id of the current process. This corresponds to the
Benjamin Petersonf650e462010-05-06 23:03:05 +0000328 "set id" bit on the file being executed in the current process.
329
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400330 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332
333.. function:: geteuid()
334
335 .. index:: single: user; effective id
336
Benjamin Petersonf650e462010-05-06 23:03:05 +0000337 Return the current process's effective user id.
338
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400339 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000340
341
342.. function:: getgid()
343
344 .. index:: single: process; group
345
Benjamin Petersonf650e462010-05-06 23:03:05 +0000346 Return the real group id of the current process.
347
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400348 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200351.. function:: getgrouplist(user, group)
352
353 Return list of group ids that *user* belongs to. If *group* is not in the
354 list, it is included; typically, *group* is specified as the group ID
355 field from the password record for *user*.
356
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400357 .. availability:: Unix.
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200358
359 .. versionadded:: 3.3
360
361
Georg Brandl116aa622007-08-15 14:28:22 +0000362.. function:: getgroups()
363
364 Return list of supplemental group ids associated with the current process.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000365
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400366 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000367
Larry Hastings3732ed22014-03-15 21:13:56 -0700368 .. note::
369
370 On Mac OS X, :func:`getgroups` behavior differs somewhat from
Ned Deily2e209682012-04-30 11:14:02 -0700371 other Unix platforms. If the Python interpreter was built with a
372 deployment target of :const:`10.5` or earlier, :func:`getgroups` returns
373 the list of effective group ids associated with the current user process;
374 this list is limited to a system-defined number of entries, typically 16,
375 and may be modified by calls to :func:`setgroups` if suitably privileged.
376 If built with a deployment target greater than :const:`10.5`,
377 :func:`getgroups` returns the current group access list for the user
378 associated with the effective user id of the process; the group access
379 list may change over the lifetime of the process, it is not affected by
380 calls to :func:`setgroups`, and its length is not limited to 16. The
381 deployment target value, :const:`MACOSX_DEPLOYMENT_TARGET`, can be
382 obtained with :func:`sysconfig.get_config_var`.
383
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385.. function:: getlogin()
386
387 Return the name of the user logged in on the controlling terminal of the
Barry Warsawd4990312018-01-24 12:51:29 -0500388 process. For most purposes, it is more useful to use
389 :func:`getpass.getuser` since the latter checks the environment variables
390 :envvar:`LOGNAME` or :envvar:`USERNAME` to find out who the user is, and
391 falls back to ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the
392 current real user id.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000393
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400394 .. availability:: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396
397.. function:: getpgid(pid)
398
399 Return the process group id of the process with process id *pid*. If *pid* is 0,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000400 the process group id of the current process is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000401
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400402 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404.. function:: getpgrp()
405
406 .. index:: single: process; group
407
Benjamin Petersonf650e462010-05-06 23:03:05 +0000408 Return the id of the current process group.
409
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400410 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412
413.. function:: getpid()
414
415 .. index:: single: process; id
416
Benjamin Petersonf650e462010-05-06 23:03:05 +0000417 Return the current process id.
418
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420.. function:: getppid()
421
422 .. index:: single: process; id of parent
423
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000424 Return the parent's process id. When the parent process has exited, on Unix
425 the id returned is the one of the init process (1), on Windows it is still
426 the same id, which may be already reused by another process.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000427
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400428 .. availability:: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000429
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000430 .. versionchanged:: 3.2
431 Added support for Windows.
Georg Brandl1b83a452009-11-28 11:12:26 +0000432
Georg Brandl8a5555f2012-06-24 13:29:09 +0200433
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000434.. function:: getpriority(which, who)
435
436 .. index:: single: process; scheduling priority
437
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200438 Get program scheduling priority. The value *which* is one of
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000439 :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
440 is interpreted relative to *which* (a process identifier for
441 :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200442 user ID for :const:`PRIO_USER`). A zero value for *who* denotes
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000443 (respectively) the calling process, the process group of the calling process,
444 or the real user ID of the calling process.
445
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400446 .. availability:: Unix.
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000447
448 .. versionadded:: 3.3
449
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200450
451.. data:: PRIO_PROCESS
452 PRIO_PGRP
453 PRIO_USER
454
455 Parameters for the :func:`getpriority` and :func:`setpriority` functions.
456
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400457 .. availability:: Unix.
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200458
459 .. versionadded:: 3.3
460
461
Gregory P. Smithcf02c6a2009-11-27 17:54:17 +0000462.. function:: getresuid()
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000463
464 Return a tuple (ruid, euid, suid) denoting the current process's
Benjamin Petersonf650e462010-05-06 23:03:05 +0000465 real, effective, and saved user ids.
466
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400467 .. availability:: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000468
Georg Brandl1b83a452009-11-28 11:12:26 +0000469 .. versionadded:: 3.2
470
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000471
Gregory P. Smithcf02c6a2009-11-27 17:54:17 +0000472.. function:: getresgid()
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000473
474 Return a tuple (rgid, egid, sgid) denoting the current process's
Georg Brandla9b51d22010-09-05 17:07:12 +0000475 real, effective, and saved group ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000476
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400477 .. availability:: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000478
Georg Brandl1b83a452009-11-28 11:12:26 +0000479 .. versionadded:: 3.2
480
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482.. function:: getuid()
483
484 .. index:: single: user; id
485
Benjamin Peterson4bb09c82014-06-07 13:50:34 -0700486 Return the current process's real user id.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000487
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400488 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000489
490
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200491.. function:: initgroups(username, gid)
Georg Brandl116aa622007-08-15 14:28:22 +0000492
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200493 Call the system initgroups() to initialize the group access list with all of
494 the groups of which the specified username is a member, plus the specified
495 group id.
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000496
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400497 .. availability:: Unix.
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000498
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200499 .. versionadded:: 3.2
500
Georg Brandl116aa622007-08-15 14:28:22 +0000501
Georg Brandl18244152009-09-02 20:34:52 +0000502.. function:: putenv(key, value)
Georg Brandl116aa622007-08-15 14:28:22 +0000503
504 .. index:: single: environment variables; setting
505
Georg Brandl18244152009-09-02 20:34:52 +0000506 Set the environment variable named *key* to the string *value*. Such
Georg Brandl116aa622007-08-15 14:28:22 +0000507 changes to the environment affect subprocesses started with :func:`os.system`,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000508 :func:`popen` or :func:`fork` and :func:`execv`.
509
Victor Stinnerb8d12622020-01-24 14:05:48 +0100510 Assignments to items in ``os.environ`` are automatically translated into
511 corresponding calls to :func:`putenv`; however, calls to :func:`putenv`
512 don't update ``os.environ``, so it is actually preferable to assign to items
513 of ``os.environ``.
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515 .. note::
516
Georg Brandlc575c902008-09-13 17:46:05 +0000517 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
Victor Stinnerb8d12622020-01-24 14:05:48 +0100518 cause memory leaks. Refer to the system documentation for :c:func:`putenv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000519
Saiyang Gou7514f4f2020-02-12 23:47:42 -0800520 .. audit-event:: os.putenv key,value os.putenv
521
Victor Stinnerb8d12622020-01-24 14:05:48 +0100522 .. versionchanged:: 3.9
523 The function is now always available.
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525
526.. function:: setegid(egid)
527
Benjamin Petersonf650e462010-05-06 23:03:05 +0000528 Set the current process's effective group id.
529
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400530 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532
533.. function:: seteuid(euid)
534
Benjamin Petersonf650e462010-05-06 23:03:05 +0000535 Set the current process's effective user id.
536
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400537 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000538
539
540.. function:: setgid(gid)
541
Benjamin Petersonf650e462010-05-06 23:03:05 +0000542 Set the current process' group id.
543
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400544 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000545
546
547.. function:: setgroups(groups)
548
549 Set the list of supplemental group ids associated with the current process to
550 *groups*. *groups* must be a sequence, and each element must be an integer
Christian Heimesfaf2f632008-01-06 16:59:19 +0000551 identifying a group. This operation is typically available only to the superuser.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000552
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400553 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000554
Ned Deily2e209682012-04-30 11:14:02 -0700555 .. note:: On Mac OS X, the length of *groups* may not exceed the
556 system-defined maximum number of effective group ids, typically 16.
557 See the documentation for :func:`getgroups` for cases where it may not
558 return the same group list set by calling setgroups().
Georg Brandl116aa622007-08-15 14:28:22 +0000559
560.. function:: setpgrp()
561
Andrew Svetlova2fe3342012-08-11 21:14:08 +0300562 Call the system call :c:func:`setpgrp` or ``setpgrp(0, 0)`` depending on
Georg Brandl116aa622007-08-15 14:28:22 +0000563 which version is implemented (if any). See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000564
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400565 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000566
567
568.. function:: setpgid(pid, pgrp)
569
Georg Brandl60203b42010-10-06 10:11:56 +0000570 Call the system call :c:func:`setpgid` to set the process group id of the
Georg Brandl116aa622007-08-15 14:28:22 +0000571 process with id *pid* to the process group with id *pgrp*. See the Unix manual
Benjamin Petersonf650e462010-05-06 23:03:05 +0000572 for the semantics.
573
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400574 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000575
576
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000577.. function:: setpriority(which, who, priority)
578
579 .. index:: single: process; scheduling priority
580
581 Set program scheduling priority. The value *which* is one of
582 :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
583 is interpreted relative to *which* (a process identifier for
584 :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
585 user ID for :const:`PRIO_USER`). A zero value for *who* denotes
586 (respectively) the calling process, the process group of the calling process,
587 or the real user ID of the calling process.
588 *priority* is a value in the range -20 to 19. The default priority is 0;
589 lower priorities cause more favorable scheduling.
590
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400591 .. availability:: Unix.
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000592
593 .. versionadded:: 3.3
594
595
Georg Brandl116aa622007-08-15 14:28:22 +0000596.. function:: setregid(rgid, egid)
597
Benjamin Petersonf650e462010-05-06 23:03:05 +0000598 Set the current process's real and effective group ids.
599
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400600 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000601
Georg Brandl1b83a452009-11-28 11:12:26 +0000602
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000603.. function:: setresgid(rgid, egid, sgid)
604
605 Set the current process's real, effective, and saved group ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000606
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400607 .. availability:: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000608
Georg Brandl1b83a452009-11-28 11:12:26 +0000609 .. versionadded:: 3.2
610
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000611
612.. function:: setresuid(ruid, euid, suid)
613
614 Set the current process's real, effective, and saved user ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000615
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400616 .. availability:: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000617
Georg Brandl1b83a452009-11-28 11:12:26 +0000618 .. versionadded:: 3.2
619
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000620
621.. function:: setreuid(ruid, euid)
622
Benjamin Petersonf650e462010-05-06 23:03:05 +0000623 Set the current process's real and effective user ids.
624
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400625 .. availability:: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000626
Georg Brandl116aa622007-08-15 14:28:22 +0000627
628.. function:: getsid(pid)
629
Georg Brandl60203b42010-10-06 10:11:56 +0000630 Call the system call :c:func:`getsid`. See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000631
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400632 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000633
Georg Brandl116aa622007-08-15 14:28:22 +0000634
635.. function:: setsid()
636
Georg Brandl60203b42010-10-06 10:11:56 +0000637 Call the system call :c:func:`setsid`. See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000638
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400639 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000640
641
642.. function:: setuid(uid)
643
644 .. index:: single: user; id, setting
645
Benjamin Petersonf650e462010-05-06 23:03:05 +0000646 Set the current process's user id.
647
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400648 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Georg Brandl116aa622007-08-15 14:28:22 +0000650
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000651.. placed in this section since it relates to errno.... a little weak
Georg Brandl116aa622007-08-15 14:28:22 +0000652.. function:: strerror(code)
653
654 Return the error message corresponding to the error code in *code*.
Georg Brandl60203b42010-10-06 10:11:56 +0000655 On platforms where :c:func:`strerror` returns ``NULL`` when given an unknown
Benjamin Petersonf650e462010-05-06 23:03:05 +0000656 error number, :exc:`ValueError` is raised.
657
Georg Brandl116aa622007-08-15 14:28:22 +0000658
Victor Stinnerb745a742010-05-18 17:17:23 +0000659.. data:: supports_bytes_environ
660
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200661 ``True`` if the native OS type of the environment is bytes (eg. ``False`` on
Victor Stinnerb745a742010-05-18 17:17:23 +0000662 Windows).
663
Victor Stinner8fddc9e2010-05-18 17:24:09 +0000664 .. versionadded:: 3.2
665
Victor Stinnerb745a742010-05-18 17:17:23 +0000666
Georg Brandl116aa622007-08-15 14:28:22 +0000667.. function:: umask(mask)
668
Benjamin Petersonf650e462010-05-06 23:03:05 +0000669 Set the current numeric umask and return the previous umask.
670
Georg Brandl116aa622007-08-15 14:28:22 +0000671
672.. function:: uname()
673
674 .. index::
675 single: gethostname() (in module socket)
676 single: gethostbyaddr() (in module socket)
677
Larry Hastings605a62d2012-06-24 04:33:36 -0700678 Returns information identifying the current operating system.
679 The return value is an object with five attributes:
680
681 * :attr:`sysname` - operating system name
682 * :attr:`nodename` - name of machine on network (implementation-defined)
683 * :attr:`release` - operating system release
684 * :attr:`version` - operating system version
685 * :attr:`machine` - hardware identifier
686
687 For backwards compatibility, this object is also iterable, behaving
688 like a five-tuple containing :attr:`sysname`, :attr:`nodename`,
689 :attr:`release`, :attr:`version`, and :attr:`machine`
690 in that order.
691
692 Some systems truncate :attr:`nodename` to 8 characters or to the
Georg Brandl116aa622007-08-15 14:28:22 +0000693 leading component; a better way to get the hostname is
694 :func:`socket.gethostname` or even
Benjamin Petersonf650e462010-05-06 23:03:05 +0000695 ``socket.gethostbyaddr(socket.gethostname())``.
696
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400697 .. availability:: recent flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Larry Hastings605a62d2012-06-24 04:33:36 -0700699 .. versionchanged:: 3.3
700 Return type changed from a tuple to a tuple-like object
701 with named attributes.
702
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Georg Brandl18244152009-09-02 20:34:52 +0000704.. function:: unsetenv(key)
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706 .. index:: single: environment variables; deleting
707
Georg Brandl18244152009-09-02 20:34:52 +0000708 Unset (delete) the environment variable named *key*. Such changes to the
Georg Brandl116aa622007-08-15 14:28:22 +0000709 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
Benjamin Petersonf650e462010-05-06 23:03:05 +0000710 :func:`fork` and :func:`execv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Victor Stinnerb8d12622020-01-24 14:05:48 +0100712 Deletion of items in ``os.environ`` is automatically translated into a
713 corresponding call to :func:`unsetenv`; however, calls to :func:`unsetenv`
714 don't update ``os.environ``, so it is actually preferable to delete items of
715 ``os.environ``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000716
Saiyang Gou7514f4f2020-02-12 23:47:42 -0800717 .. audit-event:: os.unsetenv key os.unsetenv
718
Victor Stinner161e7b32020-01-24 11:53:44 +0100719 .. versionchanged:: 3.9
Victor Stinnerb8d12622020-01-24 14:05:48 +0100720 The function is now always available and is also available on Windows.
Victor Stinner161e7b32020-01-24 11:53:44 +0100721
Georg Brandl116aa622007-08-15 14:28:22 +0000722
723.. _os-newstreams:
724
725File Object Creation
726--------------------
727
Steve Dowerb82e17e2019-05-23 08:45:22 -0700728These functions create new :term:`file objects <file object>`. (See also
Georg Brandlb2462e22012-06-24 13:24:56 +0200729:func:`~os.open` for opening file descriptors.)
Georg Brandl116aa622007-08-15 14:28:22 +0000730
731
Petri Lehtinen1a01ebc2012-05-24 21:44:07 +0300732.. function:: fdopen(fd, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Georg Brandlb2462e22012-06-24 13:24:56 +0200734 Return an open file object connected to the file descriptor *fd*. This is an
735 alias of the :func:`open` built-in function and accepts the same arguments.
736 The only difference is that the first argument of :func:`fdopen` must always
737 be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000738
Georg Brandl116aa622007-08-15 14:28:22 +0000739
Georg Brandl116aa622007-08-15 14:28:22 +0000740.. _os-fd-ops:
741
742File Descriptor Operations
743--------------------------
744
745These functions operate on I/O streams referenced using file descriptors.
746
747File descriptors are small integers corresponding to a file that has been opened
748by the current process. For example, standard input is usually file descriptor
7490, standard output is 1, and standard error is 2. Further files opened by a
750process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
751is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
752by file descriptors.
753
Serhiy Storchakadab83542013-10-13 20:12:43 +0300754The :meth:`~io.IOBase.fileno` method can be used to obtain the file descriptor
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000755associated with a :term:`file object` when required. Note that using the file
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000756descriptor directly will bypass the file object methods, ignoring aspects such
757as internal buffering of data.
Georg Brandl116aa622007-08-15 14:28:22 +0000758
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000759
Georg Brandl116aa622007-08-15 14:28:22 +0000760.. function:: close(fd)
761
Benjamin Petersonf650e462010-05-06 23:03:05 +0000762 Close file descriptor *fd*.
763
Georg Brandl116aa622007-08-15 14:28:22 +0000764 .. note::
765
766 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000767 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
Georg Brandl116aa622007-08-15 14:28:22 +0000768 object" returned by the built-in function :func:`open` or by :func:`popen` or
Serhiy Storchakadab83542013-10-13 20:12:43 +0300769 :func:`fdopen`, use its :meth:`~io.IOBase.close` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000770
771
Christian Heimesfdab48e2008-01-20 09:06:41 +0000772.. function:: closerange(fd_low, fd_high)
773
774 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
Georg Brandlb1a1ac02012-06-24 11:54:07 +0200775 ignoring errors. Equivalent to (but much faster than)::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000776
Georg Brandlc9a5a0e2009-09-01 07:34:27 +0000777 for fd in range(fd_low, fd_high):
Christian Heimesfdab48e2008-01-20 09:06:41 +0000778 try:
779 os.close(fd)
780 except OSError:
781 pass
782
Christian Heimesfdab48e2008-01-20 09:06:41 +0000783
Pablo Galindoaac4d032019-05-31 19:39:47 +0100784.. function:: copy_file_range(src, dst, count, offset_src=None, offset_dst=None)
785
786 Copy *count* bytes from file descriptor *src*, starting from offset
787 *offset_src*, to file descriptor *dst*, starting from offset *offset_dst*.
788 If *offset_src* is None, then *src* is read from the current position;
789 respectively for *offset_dst*. The files pointed by *src* and *dst*
790 must reside in the same filesystem, otherwise an :exc:`OSError` is
791 raised with :attr:`~OSError.errno` set to :data:`errno.EXDEV`.
792
793 This copy is done without the additional cost of transferring data
794 from the kernel to user space and then back into the kernel. Additionally,
795 some filesystems could implement extra optimizations. The copy is done as if
796 both files are opened as binary.
797
798 The return value is the amount of bytes copied. This could be less than the
799 amount requested.
800
801 .. availability:: Linux kernel >= 4.5 or glibc >= 2.27.
802
803 .. versionadded:: 3.8
804
805
Georg Brandl81f11302007-12-21 08:45:42 +0000806.. function:: device_encoding(fd)
807
808 Return a string describing the encoding of the device associated with *fd*
809 if it is connected to a terminal; else return :const:`None`.
810
811
Georg Brandl116aa622007-08-15 14:28:22 +0000812.. function:: dup(fd)
813
Victor Stinnerdaf45552013-08-28 00:53:59 +0200814 Return a duplicate of file descriptor *fd*. The new file descriptor is
815 :ref:`non-inheritable <fd_inheritance>`.
816
817 On Windows, when duplicating a standard stream (0: stdin, 1: stdout,
818 2: stderr), the new file descriptor is :ref:`inheritable
819 <fd_inheritance>`.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000820
Victor Stinnerdaf45552013-08-28 00:53:59 +0200821 .. versionchanged:: 3.4
822 The new file descriptor is now non-inheritable.
Georg Brandl116aa622007-08-15 14:28:22 +0000823
Victor Stinnerdaf45552013-08-28 00:53:59 +0200824
825.. function:: dup2(fd, fd2, inheritable=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000826
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -0800827 Duplicate file descriptor *fd* to *fd2*, closing the latter first if
828 necessary. Return *fd2*. The new file descriptor is :ref:`inheritable
829 <fd_inheritance>` by default or non-inheritable if *inheritable*
830 is ``False``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000831
Victor Stinnerdaf45552013-08-28 00:53:59 +0200832 .. versionchanged:: 3.4
833 Add the optional *inheritable* parameter.
834
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -0800835 .. versionchanged:: 3.7
836 Return *fd2* on success. Previously, ``None`` was always returned.
837
Georg Brandl116aa622007-08-15 14:28:22 +0000838
Christian Heimes4e30a842007-11-30 22:12:06 +0000839.. function:: fchmod(fd, mode)
840
Georg Brandlb9df00c2012-06-24 12:38:14 +0200841 Change the mode of the file given by *fd* to the numeric *mode*. See the
Georg Brandl4d399a42012-06-25 07:40:32 +0200842 docs for :func:`chmod` for possible values of *mode*. As of Python 3.3, this
Georg Brandlb9df00c2012-06-24 12:38:14 +0200843 is equivalent to ``os.chmod(fd, mode)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000844
Saiyang Gou7514f4f2020-02-12 23:47:42 -0800845 .. audit-event:: os.chmod path,mode,dir_fd os.fchmod
846
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400847 .. availability:: Unix.
Christian Heimes4e30a842007-11-30 22:12:06 +0000848
849
850.. function:: fchown(fd, uid, gid)
851
852 Change the owner and group id of the file given by *fd* to the numeric *uid*
Georg Brandlb9df00c2012-06-24 12:38:14 +0200853 and *gid*. To leave one of the ids unchanged, set it to -1. See
Georg Brandl4d399a42012-06-25 07:40:32 +0200854 :func:`chown`. As of Python 3.3, this is equivalent to ``os.chown(fd, uid,
Georg Brandlb9df00c2012-06-24 12:38:14 +0200855 gid)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000856
Saiyang Gou7514f4f2020-02-12 23:47:42 -0800857 .. audit-event:: os.chown path,uid,gid,dir_fd os.fchown
858
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400859 .. availability:: Unix.
Christian Heimes4e30a842007-11-30 22:12:06 +0000860
861
Georg Brandl116aa622007-08-15 14:28:22 +0000862.. function:: fdatasync(fd)
863
864 Force write of file with filedescriptor *fd* to disk. Does not force update of
Benjamin Petersonf650e462010-05-06 23:03:05 +0000865 metadata.
866
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400867 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000868
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000869 .. note::
870 This function is not available on MacOS.
871
Georg Brandl116aa622007-08-15 14:28:22 +0000872
873.. function:: fpathconf(fd, name)
874
875 Return system configuration information relevant to an open file. *name*
876 specifies the configuration value to retrieve; it may be a string which is the
877 name of a defined system value; these names are specified in a number of
878 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
879 additional names as well. The names known to the host operating system are
880 given in the ``pathconf_names`` dictionary. For configuration variables not
881 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +0000882
883 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
884 specific value for *name* is not supported by the host system, even if it is
885 included in ``pathconf_names``, an :exc:`OSError` is raised with
886 :const:`errno.EINVAL` for the error number.
887
Georg Brandl4d399a42012-06-25 07:40:32 +0200888 As of Python 3.3, this is equivalent to ``os.pathconf(fd, name)``.
Georg Brandl306336b2012-06-24 12:55:33 +0200889
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400890 .. availability:: Unix.
Senthil Kumaran2a97cee2013-09-19 00:08:56 -0700891
Georg Brandl116aa622007-08-15 14:28:22 +0000892
Victor Stinner4195b5c2012-02-08 23:03:19 +0100893.. function:: fstat(fd)
Georg Brandl116aa622007-08-15 14:28:22 +0000894
Victor Stinner6d4f4fe2014-07-24 12:42:16 +0200895 Get the status of the file descriptor *fd*. Return a :class:`stat_result`
896 object.
897
898 As of Python 3.3, this is equivalent to ``os.stat(fd)``.
899
900 .. seealso::
901
Berker Peksag2034caa2015-04-27 13:53:28 +0300902 The :func:`.stat` function.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000903
Georg Brandlb1a1ac02012-06-24 11:54:07 +0200904
Georg Brandl116aa622007-08-15 14:28:22 +0000905.. function:: fstatvfs(fd)
906
Georg Brandlb9df00c2012-06-24 12:38:14 +0200907 Return information about the filesystem containing the file associated with
Georg Brandl4d399a42012-06-25 07:40:32 +0200908 file descriptor *fd*, like :func:`statvfs`. As of Python 3.3, this is
Georg Brandlb9df00c2012-06-24 12:38:14 +0200909 equivalent to ``os.statvfs(fd)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000910
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400911 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000912
913
914.. function:: fsync(fd)
915
916 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
Georg Brandl60203b42010-10-06 10:11:56 +0000917 native :c:func:`fsync` function; on Windows, the MS :c:func:`_commit` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000918
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000919 If you're starting with a buffered Python :term:`file object` *f*, first do
920 ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal
921 buffers associated with *f* are written to disk.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000922
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400923 .. availability:: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000924
925
926.. function:: ftruncate(fd, length)
927
Georg Brandl306336b2012-06-24 12:55:33 +0200928 Truncate the file corresponding to file descriptor *fd*, so that it is at
Georg Brandl4d399a42012-06-25 07:40:32 +0200929 most *length* bytes in size. As of Python 3.3, this is equivalent to
Georg Brandl306336b2012-06-24 12:55:33 +0200930 ``os.truncate(fd, length)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000931
Steve Dower44f91c32019-06-27 10:47:59 -0700932 .. audit-event:: os.truncate fd,length os.ftruncate
Steve Dowerb82e17e2019-05-23 08:45:22 -0700933
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400934 .. availability:: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Steve Dowerfe0a41a2015-03-20 19:50:46 -0700936 .. versionchanged:: 3.5
937 Added support for Windows
Georg Brandl116aa622007-08-15 14:28:22 +0000938
Steve Dowerb82e17e2019-05-23 08:45:22 -0700939
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200940.. function:: get_blocking(fd)
941
942 Get the blocking mode of the file descriptor: ``False`` if the
943 :data:`O_NONBLOCK` flag is set, ``True`` if the flag is cleared.
944
945 See also :func:`set_blocking` and :meth:`socket.socket.setblocking`.
946
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400947 .. availability:: Unix.
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200948
949 .. versionadded:: 3.5
950
Steve Dowerb82e17e2019-05-23 08:45:22 -0700951
Georg Brandl116aa622007-08-15 14:28:22 +0000952.. function:: isatty(fd)
953
954 Return ``True`` if the file descriptor *fd* is open and connected to a
Benjamin Petersonf650e462010-05-06 23:03:05 +0000955 tty(-like) device, else ``False``.
956
Georg Brandl116aa622007-08-15 14:28:22 +0000957
Ross Lagerwall7807c352011-03-17 20:20:30 +0200958.. function:: lockf(fd, cmd, len)
959
960 Apply, test or remove a POSIX lock on an open file descriptor.
961 *fd* is an open file descriptor.
962 *cmd* specifies the command to use - one of :data:`F_LOCK`, :data:`F_TLOCK`,
963 :data:`F_ULOCK` or :data:`F_TEST`.
964 *len* specifies the section of the file to lock.
965
Saiyang Gou7514f4f2020-02-12 23:47:42 -0800966 .. audit-event:: os.lockf fd,cmd,len os.lockf
967
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400968 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +0200969
970 .. versionadded:: 3.3
971
972
973.. data:: F_LOCK
974 F_TLOCK
975 F_ULOCK
976 F_TEST
977
978 Flags that specify what action :func:`lockf` will take.
979
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400980 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +0200981
982 .. versionadded:: 3.3
983
Georg Brandlf62445a2012-06-24 13:31:20 +0200984
Georg Brandl116aa622007-08-15 14:28:22 +0000985.. function:: lseek(fd, pos, how)
986
Christian Heimesfaf2f632008-01-06 16:59:19 +0000987 Set the current position of file descriptor *fd* to position *pos*, modified
988 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
989 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
Serhiy Storchakadab83542013-10-13 20:12:43 +0300990 current position; :const:`SEEK_END` or ``2`` to set it relative to the end of
Victor Stinnere83f8992011-12-17 23:15:09 +0100991 the file. Return the new cursor position in bytes, starting from the beginning.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000992
Georg Brandl116aa622007-08-15 14:28:22 +0000993
Georg Brandl8569e582010-05-19 20:57:08 +0000994.. data:: SEEK_SET
995 SEEK_CUR
996 SEEK_END
997
998 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
Georg Brandl8a5555f2012-06-24 13:29:09 +0200999 respectively.
1000
Jesus Cea94363612012-06-22 18:32:07 +02001001 .. versionadded:: 3.3
1002 Some operating systems could support additional values, like
1003 :data:`os.SEEK_HOLE` or :data:`os.SEEK_DATA`.
1004
Georg Brandl8569e582010-05-19 20:57:08 +00001005
Martin Panterbf19d162015-09-09 01:01:13 +00001006.. function:: open(path, flags, mode=0o777, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001007
Martin Panterbf19d162015-09-09 01:01:13 +00001008 Open the file *path* and set various flags according to *flags* and possibly
Larry Hastings9cf065c2012-06-22 16:30:09 -07001009 its mode according to *mode*. When computing *mode*, the current umask value
1010 is first masked out. Return the file descriptor for the newly opened file.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001011 The new file descriptor is :ref:`non-inheritable <fd_inheritance>`.
Georg Brandl116aa622007-08-15 14:28:22 +00001012
1013 For a description of the flag and mode values, see the C run-time documentation;
1014 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
Andrew Kuchling4921a082013-06-21 11:49:57 -04001015 the :mod:`os` module. In particular, on Windows adding
Georg Brandl8569e582010-05-19 20:57:08 +00001016 :const:`O_BINARY` is needed to open files in binary mode.
Georg Brandl116aa622007-08-15 14:28:22 +00001017
Georg Brandl50c40002012-06-24 11:45:20 +02001018 This function can support :ref:`paths relative to directory descriptors
Andrew Kuchling4921a082013-06-21 11:49:57 -04001019 <dir_fd>` with the *dir_fd* parameter.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001020
Steve Dower44f91c32019-06-27 10:47:59 -07001021 .. audit-event:: open path,mode,flags os.open
Steve Dowerb82e17e2019-05-23 08:45:22 -07001022
Victor Stinnerdaf45552013-08-28 00:53:59 +02001023 .. versionchanged:: 3.4
1024 The new file descriptor is now non-inheritable.
1025
Georg Brandl116aa622007-08-15 14:28:22 +00001026 .. note::
1027
Georg Brandl502d9a52009-07-26 15:02:41 +00001028 This function is intended for low-level I/O. For normal usage, use the
Antoine Pitrou11cb9612010-09-15 11:11:28 +00001029 built-in function :func:`open`, which returns a :term:`file object` with
Jeroen Ruigrok van der Werven9c558bcf2010-07-13 14:47:01 +00001030 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
Antoine Pitrou11cb9612010-09-15 11:11:28 +00001031 wrap a file descriptor in a file object, use :func:`fdopen`.
Georg Brandl116aa622007-08-15 14:28:22 +00001032
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001033 .. versionadded:: 3.3
Larry Hastings9cf065c2012-06-22 16:30:09 -07001034 The *dir_fd* argument.
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001035
Victor Stinnera766ddf2015-03-26 23:50:57 +01001036 .. versionchanged:: 3.5
Victor Stinner708d9ba2015-04-02 11:49:42 +02001037 If the system call is interrupted and the signal handler does not raise an
Victor Stinnera766ddf2015-03-26 23:50:57 +01001038 exception, the function now retries the system call instead of raising an
1039 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1040
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001041 .. versionchanged:: 3.6
1042 Accepts a :term:`path-like object`.
1043
Andrew Kuchling4921a082013-06-21 11:49:57 -04001044The following constants are options for the *flags* parameter to the
1045:func:`~os.open` function. They can be combined using the bitwise OR operator
1046``|``. Some of them are not available on all platforms. For descriptions of
1047their availability and use, consult the :manpage:`open(2)` manual page on Unix
Georg Brandl5d941342016-02-26 19:37:12 +01001048or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
Andrew Kuchling4921a082013-06-21 11:49:57 -04001049
1050
1051.. data:: O_RDONLY
1052 O_WRONLY
1053 O_RDWR
1054 O_APPEND
1055 O_CREAT
1056 O_EXCL
1057 O_TRUNC
1058
Vinay Sajipe4946e72016-09-11 15:15:59 +01001059 The above constants are available on Unix and Windows.
Andrew Kuchling4921a082013-06-21 11:49:57 -04001060
1061
1062.. data:: O_DSYNC
1063 O_RSYNC
1064 O_SYNC
1065 O_NDELAY
1066 O_NONBLOCK
1067 O_NOCTTY
Andrew Kuchling4921a082013-06-21 11:49:57 -04001068 O_CLOEXEC
1069
Vinay Sajipe4946e72016-09-11 15:15:59 +01001070 The above constants are only available on Unix.
Andrew Kuchling4921a082013-06-21 11:49:57 -04001071
1072 .. versionchanged:: 3.3
1073 Add :data:`O_CLOEXEC` constant.
1074
1075.. data:: O_BINARY
1076 O_NOINHERIT
1077 O_SHORT_LIVED
1078 O_TEMPORARY
1079 O_RANDOM
1080 O_SEQUENTIAL
1081 O_TEXT
1082
Vinay Sajipe4946e72016-09-11 15:15:59 +01001083 The above constants are only available on Windows.
Andrew Kuchling4921a082013-06-21 11:49:57 -04001084
1085
1086.. data:: O_ASYNC
1087 O_DIRECT
1088 O_DIRECTORY
1089 O_NOFOLLOW
1090 O_NOATIME
1091 O_PATH
Christian Heimes177b3f92013-08-16 14:35:09 +02001092 O_TMPFILE
Vinay Sajipe4946e72016-09-11 15:15:59 +01001093 O_SHLOCK
1094 O_EXLOCK
Andrew Kuchling4921a082013-06-21 11:49:57 -04001095
Vinay Sajipe4946e72016-09-11 15:15:59 +01001096 The above constants are extensions and not present if they are not defined by
Andrew Kuchling4921a082013-06-21 11:49:57 -04001097 the C library.
1098
Christian Heimesd88f7352013-08-16 14:37:50 +02001099 .. versionchanged:: 3.4
Larry Hastings3732ed22014-03-15 21:13:56 -07001100 Add :data:`O_PATH` on systems that support it.
1101 Add :data:`O_TMPFILE`, only available on Linux Kernel 3.11
1102 or newer.
Christian Heimesd88f7352013-08-16 14:37:50 +02001103
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001104
Georg Brandl116aa622007-08-15 14:28:22 +00001105.. function:: openpty()
1106
1107 .. index:: module: pty
1108
Victor Stinnerdaf45552013-08-28 00:53:59 +02001109 Open a new pseudo-terminal pair. Return a pair of file descriptors
1110 ``(master, slave)`` for the pty and the tty, respectively. The new file
1111 descriptors are :ref:`non-inheritable <fd_inheritance>`. For a (slightly) more
1112 portable approach, use the :mod:`pty` module.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001113
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001114 .. availability:: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001115
Victor Stinnerdaf45552013-08-28 00:53:59 +02001116 .. versionchanged:: 3.4
1117 The new file descriptors are now non-inheritable.
1118
Georg Brandl116aa622007-08-15 14:28:22 +00001119
1120.. function:: pipe()
1121
Victor Stinnerdaf45552013-08-28 00:53:59 +02001122 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for
Victor Stinner05f31bf2013-11-06 01:48:45 +01001123 reading and writing, respectively. The new file descriptor is
Victor Stinnerdaf45552013-08-28 00:53:59 +02001124 :ref:`non-inheritable <fd_inheritance>`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001125
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001126 .. availability:: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001127
Victor Stinnerdaf45552013-08-28 00:53:59 +02001128 .. versionchanged:: 3.4
1129 The new file descriptors are now non-inheritable.
1130
Georg Brandl116aa622007-08-15 14:28:22 +00001131
Charles-François Natali368f34b2011-06-06 19:49:47 +02001132.. function:: pipe2(flags)
Charles-François Natalidaafdd52011-05-29 20:07:40 +02001133
1134 Create a pipe with *flags* set atomically.
Charles-François Natali368f34b2011-06-06 19:49:47 +02001135 *flags* can be constructed by ORing together one or more of these values:
1136 :data:`O_NONBLOCK`, :data:`O_CLOEXEC`.
Charles-François Natalidaafdd52011-05-29 20:07:40 +02001137 Return a pair of file descriptors ``(r, w)`` usable for reading and writing,
1138 respectively.
1139
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001140 .. availability:: some flavors of Unix.
Charles-François Natalidaafdd52011-05-29 20:07:40 +02001141
1142 .. versionadded:: 3.3
1143
1144
Ross Lagerwall7807c352011-03-17 20:20:30 +02001145.. function:: posix_fallocate(fd, offset, len)
1146
1147 Ensures that enough disk space is allocated for the file specified by *fd*
1148 starting from *offset* and continuing for *len* bytes.
1149
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001150 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001151
1152 .. versionadded:: 3.3
1153
1154
1155.. function:: posix_fadvise(fd, offset, len, advice)
1156
1157 Announces an intention to access data in a specific pattern thus allowing
1158 the kernel to make optimizations.
1159 The advice applies to the region of the file specified by *fd* starting at
1160 *offset* and continuing for *len* bytes.
1161 *advice* is one of :data:`POSIX_FADV_NORMAL`, :data:`POSIX_FADV_SEQUENTIAL`,
1162 :data:`POSIX_FADV_RANDOM`, :data:`POSIX_FADV_NOREUSE`,
1163 :data:`POSIX_FADV_WILLNEED` or :data:`POSIX_FADV_DONTNEED`.
1164
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001165 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001166
1167 .. versionadded:: 3.3
1168
1169
1170.. data:: POSIX_FADV_NORMAL
1171 POSIX_FADV_SEQUENTIAL
1172 POSIX_FADV_RANDOM
1173 POSIX_FADV_NOREUSE
1174 POSIX_FADV_WILLNEED
1175 POSIX_FADV_DONTNEED
1176
1177 Flags that can be used in *advice* in :func:`posix_fadvise` that specify
1178 the access pattern that is likely to be used.
1179
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001180 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001181
1182 .. versionadded:: 3.3
1183
1184
Pablo Galindo02e2a082018-05-31 00:00:04 +01001185.. function:: pread(fd, n, offset)
Ross Lagerwall7807c352011-03-17 20:20:30 +02001186
Pablo Galindo02e2a082018-05-31 00:00:04 +01001187 Read at most *n* bytes from file descriptor *fd* at a position of *offset*,
1188 leaving the file offset unchanged.
1189
1190 Return a bytestring containing the bytes read. If the end of the file
1191 referred to by *fd* has been reached, an empty bytes object is returned.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001192
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001193 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001194
1195 .. versionadded:: 3.3
1196
1197
Pablo Galindo02e2a082018-05-31 00:00:04 +01001198.. function:: preadv(fd, buffers, offset, flags=0)
1199
1200 Read from a file descriptor *fd* at a position of *offset* into mutable
1201 :term:`bytes-like objects <bytes-like object>` *buffers*, leaving the file
1202 offset unchanged. Transfer data into each buffer until it is full and then
1203 move on to the next buffer in the sequence to hold the rest of the data.
1204
1205 The flags argument contains a bitwise OR of zero or more of the following
1206 flags:
1207
1208 - :data:`RWF_HIPRI`
1209 - :data:`RWF_NOWAIT`
1210
1211 Return the total number of bytes actually read which can be less than the
1212 total capacity of all the objects.
1213
1214 The operating system may set a limit (:func:`sysconf` value
1215 ``'SC_IOV_MAX'``) on the number of buffers that can be used.
1216
1217 Combine the functionality of :func:`os.readv` and :func:`os.pread`.
1218
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001219 .. availability:: Linux 2.6.30 and newer, FreeBSD 6.0 and newer,
Batuhan Taskayacae22752020-05-17 01:36:40 +03001220 OpenBSD 2.7 and newer, AIX 7.1 and newer. Using flags requires
1221 Linux 4.6 or newer.
Pablo Galindo02e2a082018-05-31 00:00:04 +01001222
1223 .. versionadded:: 3.7
1224
1225
1226.. data:: RWF_NOWAIT
1227
1228 Do not wait for data which is not immediately available. If this flag is
1229 specified, the system call will return instantly if it would have to read
1230 data from the backing storage or wait for a lock.
1231
1232 If some data was successfully read, it will return the number of bytes read.
1233 If no bytes were read, it will return ``-1`` and set errno to
1234 :data:`errno.EAGAIN`.
1235
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001236 .. availability:: Linux 4.14 and newer.
Pablo Galindo02e2a082018-05-31 00:00:04 +01001237
1238 .. versionadded:: 3.7
1239
1240
1241.. data:: RWF_HIPRI
1242
1243 High priority read/write. Allows block-based filesystems to use polling
1244 of the device, which provides lower latency, but may use additional
1245 resources.
1246
1247 Currently, on Linux, this feature is usable only on a file descriptor opened
1248 using the :data:`O_DIRECT` flag.
1249
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001250 .. availability:: Linux 4.6 and newer.
Pablo Galindo02e2a082018-05-31 00:00:04 +01001251
1252 .. versionadded:: 3.7
1253
1254
Jesus Cea67503c52014-10-20 16:18:24 +02001255.. function:: pwrite(fd, str, offset)
Ross Lagerwall7807c352011-03-17 20:20:30 +02001256
Pablo Galindo02e2a082018-05-31 00:00:04 +01001257 Write the bytestring in *str* to file descriptor *fd* at position of
1258 *offset*, leaving the file offset unchanged.
1259
1260 Return the number of bytes actually written.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001261
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001262 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001263
1264 .. versionadded:: 3.3
1265
1266
Pablo Galindo4defba32018-01-27 16:16:37 +00001267.. function:: pwritev(fd, buffers, offset, flags=0)
1268
Pablo Galindo02e2a082018-05-31 00:00:04 +01001269 Write the *buffers* contents to file descriptor *fd* at a offset *offset*,
1270 leaving the file offset unchanged. *buffers* must be a sequence of
1271 :term:`bytes-like objects <bytes-like object>`. Buffers are processed in
1272 array order. Entire contents of the first buffer is written before
1273 proceeding to the second, and so on.
Pablo Galindo4defba32018-01-27 16:16:37 +00001274
Pablo Galindo02e2a082018-05-31 00:00:04 +01001275 The flags argument contains a bitwise OR of zero or more of the following
Pablo Galindo4defba32018-01-27 16:16:37 +00001276 flags:
1277
Pablo Galindo02e2a082018-05-31 00:00:04 +01001278 - :data:`RWF_DSYNC`
1279 - :data:`RWF_SYNC`
YoSTEALTH76ef2552020-05-27 15:32:22 -06001280 - :data:`RWF_APPEND`
Pablo Galindo4defba32018-01-27 16:16:37 +00001281
Pablo Galindo02e2a082018-05-31 00:00:04 +01001282 Return the total number of bytes actually written.
Pablo Galindo4defba32018-01-27 16:16:37 +00001283
Pablo Galindo02e2a082018-05-31 00:00:04 +01001284 The operating system may set a limit (:func:`sysconf` value
1285 ``'SC_IOV_MAX'``) on the number of buffers that can be used.
1286
1287 Combine the functionality of :func:`os.writev` and :func:`os.pwrite`.
1288
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001289 .. availability:: Linux 2.6.30 and newer, FreeBSD 6.0 and newer,
Batuhan Taskayacae22752020-05-17 01:36:40 +03001290 OpenBSD 2.7 and newer, AIX 7.1 and newer. Using flags requires
1291 Linux 4.7 or newer.
Pablo Galindo4defba32018-01-27 16:16:37 +00001292
1293 .. versionadded:: 3.7
1294
Pablo Galindo02e2a082018-05-31 00:00:04 +01001295
Pablo Galindod6ef6db2018-04-25 18:48:27 +01001296.. data:: RWF_DSYNC
1297
YoSTEALTH76ef2552020-05-27 15:32:22 -06001298 Provide a per-write equivalent of the :data:`O_DSYNC` :func:`os.open` flag.
1299 This flag effect applies only to the data range written by the system call.
Pablo Galindo4defba32018-01-27 16:16:37 +00001300
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001301 .. availability:: Linux 4.7 and newer.
Pablo Galindod6ef6db2018-04-25 18:48:27 +01001302
Pablo Galindo4defba32018-01-27 16:16:37 +00001303 .. versionadded:: 3.7
1304
Pablo Galindo02e2a082018-05-31 00:00:04 +01001305
Pablo Galindod6ef6db2018-04-25 18:48:27 +01001306.. data:: RWF_SYNC
1307
YoSTEALTH76ef2552020-05-27 15:32:22 -06001308 Provide a per-write equivalent of the :data:`O_SYNC` :func:`os.open` flag.
1309 This flag effect applies only to the data range written by the system call.
Pablo Galindo4defba32018-01-27 16:16:37 +00001310
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001311 .. availability:: Linux 4.7 and newer.
Pablo Galindod6ef6db2018-04-25 18:48:27 +01001312
Pablo Galindo4defba32018-01-27 16:16:37 +00001313 .. versionadded:: 3.7
1314
1315
YoSTEALTH76ef2552020-05-27 15:32:22 -06001316.. data:: RWF_APPEND
1317
1318 Provide a per-write equivalent of the :data:`O_APPEND` :func:`os.open`
1319 flag. This flag is meaningful only for :func:`os.pwritev`, and its
1320 effect applies only to the data range written by the system call. The
1321 *offset* argument does not affect the write operation; the data is always
1322 appended to the end of the file. However, if the *offset* argument is
1323 ``-1``, the current file *offset* is updated.
1324
1325 .. availability:: Linux 4.16 and newer.
1326
1327 .. versionadded:: 3.10
1328
1329
Georg Brandl116aa622007-08-15 14:28:22 +00001330.. function:: read(fd, n)
1331
Pablo Galindo02e2a082018-05-31 00:00:04 +01001332 Read at most *n* bytes from file descriptor *fd*.
1333
1334 Return a bytestring containing the bytes read. If the end of the file
1335 referred to by *fd* has been reached, an empty bytes object is returned.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001336
Georg Brandl116aa622007-08-15 14:28:22 +00001337 .. note::
1338
1339 This function is intended for low-level I/O and must be applied to a file
Georg Brandlb2462e22012-06-24 13:24:56 +02001340 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a
1341 "file object" returned by the built-in function :func:`open` or by
1342 :func:`popen` or :func:`fdopen`, or :data:`sys.stdin`, use its
1343 :meth:`~file.read` or :meth:`~file.readline` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00001344
Victor Stinnera766ddf2015-03-26 23:50:57 +01001345 .. versionchanged:: 3.5
Victor Stinner708d9ba2015-04-02 11:49:42 +02001346 If the system call is interrupted and the signal handler does not raise an
Victor Stinnera766ddf2015-03-26 23:50:57 +01001347 exception, the function now retries the system call instead of raising an
1348 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1349
Georg Brandl116aa622007-08-15 14:28:22 +00001350
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03001351.. function:: sendfile(out_fd, in_fd, offset, count)
Serhiy Storchaka2b560312020-04-18 19:14:10 +03001352 sendfile(out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001353
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03001354 Copy *count* bytes from file descriptor *in_fd* to file descriptor *out_fd*
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001355 starting at *offset*.
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03001356 Return the number of bytes sent. When EOF is reached return ``0``.
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001357
1358 The first function notation is supported by all platforms that define
1359 :func:`sendfile`.
1360
1361 On Linux, if *offset* is given as ``None``, the bytes are read from the
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03001362 current position of *in_fd* and the position of *in_fd* is updated.
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001363
1364 The second case may be used on Mac OS X and FreeBSD where *headers* and
1365 *trailers* are arbitrary sequences of buffers that are written before and
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03001366 after the data from *in_fd* is written. It returns the same as the first case.
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001367
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03001368 On Mac OS X and FreeBSD, a value of ``0`` for *count* specifies to send until
1369 the end of *in_fd* is reached.
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001370
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03001371 All platforms support sockets as *out_fd* file descriptor, and some platforms
Charles-Francois Natalia771a1b2013-05-01 15:12:20 +02001372 allow other types (e.g. regular file, pipe) as well.
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001373
Giampaolo Rodola'409569b2014-04-24 18:09:21 +02001374 Cross-platform applications should not use *headers*, *trailers* and *flags*
1375 arguments.
1376
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001377 .. availability:: Unix.
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001378
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02001379 .. note::
1380
Benjamin Peterson0ce95372014-06-15 18:30:27 -07001381 For a higher-level wrapper of :func:`sendfile`, see
Martin Panter3133a9f2015-09-11 23:44:18 +00001382 :meth:`socket.socket.sendfile`.
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02001383
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001384 .. versionadded:: 3.3
1385
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03001386 .. versionchanged:: 3.9
1387 Parameters *out* and *in* was renamed to *out_fd* and *in_fd*.
1388
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001389
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001390.. function:: set_blocking(fd, blocking)
1391
1392 Set the blocking mode of the specified file descriptor. Set the
1393 :data:`O_NONBLOCK` flag if blocking is ``False``, clear the flag otherwise.
1394
1395 See also :func:`get_blocking` and :meth:`socket.socket.setblocking`.
1396
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001397 .. availability:: Unix.
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001398
1399 .. versionadded:: 3.5
1400
1401
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001402.. data:: SF_NODISKIO
1403 SF_MNOWAIT
1404 SF_SYNC
1405
1406 Parameters to the :func:`sendfile` function, if the implementation supports
1407 them.
1408
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001409 .. availability:: Unix.
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001410
1411 .. versionadded:: 3.3
1412
1413
Ross Lagerwall7807c352011-03-17 20:20:30 +02001414.. function:: readv(fd, buffers)
1415
Benjamin Petersone83ed432014-01-18 22:54:59 -05001416 Read from a file descriptor *fd* into a number of mutable :term:`bytes-like
Pablo Galindo02e2a082018-05-31 00:00:04 +01001417 objects <bytes-like object>` *buffers*. Transfer data into each buffer until
1418 it is full and then move on to the next buffer in the sequence to hold the
1419 rest of the data.
1420
1421 Return the total number of bytes actually read which can be less than the
1422 total capacity of all the objects.
1423
1424 The operating system may set a limit (:func:`sysconf` value
1425 ``'SC_IOV_MAX'``) on the number of buffers that can be used.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001426
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001427 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001428
1429 .. versionadded:: 3.3
1430
1431
Georg Brandl116aa622007-08-15 14:28:22 +00001432.. function:: tcgetpgrp(fd)
1433
1434 Return the process group associated with the terminal given by *fd* (an open
Benjamin Petersonf650e462010-05-06 23:03:05 +00001435 file descriptor as returned by :func:`os.open`).
1436
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001437 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001438
1439
1440.. function:: tcsetpgrp(fd, pg)
1441
1442 Set the process group associated with the terminal given by *fd* (an open file
Benjamin Petersonf650e462010-05-06 23:03:05 +00001443 descriptor as returned by :func:`os.open`) to *pg*.
1444
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001445 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001446
1447
1448.. function:: ttyname(fd)
1449
1450 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +00001451 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Benjamin Petersonf650e462010-05-06 23:03:05 +00001452 exception is raised.
1453
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001454 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001455
1456
1457.. function:: write(fd, str)
1458
Pablo Galindo02e2a082018-05-31 00:00:04 +01001459 Write the bytestring in *str* to file descriptor *fd*.
1460
1461 Return the number of bytes actually written.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001462
Georg Brandl116aa622007-08-15 14:28:22 +00001463 .. note::
1464
1465 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001466 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
Georg Brandl116aa622007-08-15 14:28:22 +00001467 object" returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001468 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
1469 :meth:`~file.write` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001470
Victor Stinnera766ddf2015-03-26 23:50:57 +01001471 .. versionchanged:: 3.5
Victor Stinner708d9ba2015-04-02 11:49:42 +02001472 If the system call is interrupted and the signal handler does not raise an
Victor Stinnera766ddf2015-03-26 23:50:57 +01001473 exception, the function now retries the system call instead of raising an
1474 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1475
Georg Brandl8569e582010-05-19 20:57:08 +00001476
Ross Lagerwall7807c352011-03-17 20:20:30 +02001477.. function:: writev(fd, buffers)
1478
Pablo Galindo02e2a082018-05-31 00:00:04 +01001479 Write the contents of *buffers* to file descriptor *fd*. *buffers* must be
1480 a sequence of :term:`bytes-like objects <bytes-like object>`. Buffers are
1481 processed in array order. Entire contents of the first buffer is written
1482 before proceeding to the second, and so on.
Senthil Kumarand37de3c2016-06-18 11:21:50 -07001483
Pablo Galindo02e2a082018-05-31 00:00:04 +01001484 Returns the total number of bytes actually written.
1485
1486 The operating system may set a limit (:func:`sysconf` value
1487 ``'SC_IOV_MAX'``) on the number of buffers that can be used.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001488
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001489 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001490
1491 .. versionadded:: 3.3
1492
1493
Antoine Pitroubcf2b592012-02-08 23:28:36 +01001494.. _terminal-size:
1495
1496Querying the size of a terminal
1497~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1498
1499.. versionadded:: 3.3
1500
1501.. function:: get_terminal_size(fd=STDOUT_FILENO)
1502
1503 Return the size of the terminal window as ``(columns, lines)``,
1504 tuple of type :class:`terminal_size`.
1505
1506 The optional argument ``fd`` (default ``STDOUT_FILENO``, or standard
1507 output) specifies which file descriptor should be queried.
1508
1509 If the file descriptor is not connected to a terminal, an :exc:`OSError`
Andrew Svetlov5b898402012-12-18 21:26:36 +02001510 is raised.
Antoine Pitroubcf2b592012-02-08 23:28:36 +01001511
1512 :func:`shutil.get_terminal_size` is the high-level function which
1513 should normally be used, ``os.get_terminal_size`` is the low-level
1514 implementation.
1515
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001516 .. availability:: Unix, Windows.
Antoine Pitroubcf2b592012-02-08 23:28:36 +01001517
Georg Brandl6cff9ff2012-06-24 14:05:40 +02001518.. class:: terminal_size
Antoine Pitroubcf2b592012-02-08 23:28:36 +01001519
Georg Brandl6cff9ff2012-06-24 14:05:40 +02001520 A subclass of tuple, holding ``(columns, lines)`` of the terminal window size.
Antoine Pitroubcf2b592012-02-08 23:28:36 +01001521
1522 .. attribute:: columns
1523
1524 Width of the terminal window in characters.
1525
1526 .. attribute:: lines
1527
1528 Height of the terminal window in characters.
1529
1530
Victor Stinnerdaf45552013-08-28 00:53:59 +02001531.. _fd_inheritance:
1532
1533Inheritance of File Descriptors
1534~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1535
Georg Brandl5642ff92013-09-15 10:37:57 +02001536.. versionadded:: 3.4
1537
1538A file descriptor has an "inheritable" flag which indicates if the file descriptor
1539can be inherited by child processes. Since Python 3.4, file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001540created by Python are non-inheritable by default.
1541
1542On UNIX, non-inheritable file descriptors are closed in child processes at the
1543execution of a new program, other file descriptors are inherited.
1544
1545On Windows, non-inheritable handles and file descriptors are closed in child
Georg Brandl5642ff92013-09-15 10:37:57 +02001546processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout
Serhiy Storchaka690a6a92013-10-13 20:13:37 +03001547and stderr), which are always inherited. Using :func:`spawn\* <spawnl>` functions,
Victor Stinnerdaf45552013-08-28 00:53:59 +02001548all inheritable handles and all inheritable file descriptors are inherited.
1549Using the :mod:`subprocess` module, all file descriptors except standard
Georg Brandl5642ff92013-09-15 10:37:57 +02001550streams are closed, and inheritable handles are only inherited if the
1551*close_fds* parameter is ``False``.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001552
1553.. function:: get_inheritable(fd)
1554
Georg Brandl5642ff92013-09-15 10:37:57 +02001555 Get the "inheritable" flag of the specified file descriptor (a boolean).
Victor Stinnerdaf45552013-08-28 00:53:59 +02001556
1557.. function:: set_inheritable(fd, inheritable)
1558
Georg Brandl5642ff92013-09-15 10:37:57 +02001559 Set the "inheritable" flag of the specified file descriptor.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001560
1561.. function:: get_handle_inheritable(handle)
1562
Georg Brandl5642ff92013-09-15 10:37:57 +02001563 Get the "inheritable" flag of the specified handle (a boolean).
Victor Stinnerdaf45552013-08-28 00:53:59 +02001564
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001565 .. availability:: Windows.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001566
1567.. function:: set_handle_inheritable(handle, inheritable)
1568
Georg Brandl5642ff92013-09-15 10:37:57 +02001569 Set the "inheritable" flag of the specified handle.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001570
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001571 .. availability:: Windows.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001572
1573
Georg Brandl116aa622007-08-15 14:28:22 +00001574.. _os-file-dir:
1575
1576Files and Directories
1577---------------------
1578
Georg Brandl50c40002012-06-24 11:45:20 +02001579On some Unix platforms, many of these functions support one or more of these
1580features:
1581
1582.. _path_fd:
1583
Larry Hastings77892dc2012-06-25 03:27:33 -07001584* **specifying a file descriptor:**
Cheryl Sabellae1521692019-05-06 08:39:13 -04001585 Normally the *path* argument provided to functions in the :mod:`os` module
1586 must be a string specifying a file path. However, some functions now
1587 alternatively accept an open file descriptor for their *path* argument.
1588 The function will then operate on the file referred to by the descriptor.
1589 (For POSIX systems, Python will call the variant of the function prefixed
1590 with ``f`` (e.g. call ``fchdir`` instead of ``chdir``).)
Georg Brandl50c40002012-06-24 11:45:20 +02001591
Cheryl Sabellae1521692019-05-06 08:39:13 -04001592 You can check whether or not *path* can be specified as a file descriptor
1593 for a particular function on your platform using :data:`os.supports_fd`.
1594 If this functionality is unavailable, using it will raise a
1595 :exc:`NotImplementedError`.
Georg Brandl50c40002012-06-24 11:45:20 +02001596
Cheryl Sabellae1521692019-05-06 08:39:13 -04001597 If the function also supports *dir_fd* or *follow_symlinks* arguments, it's
Georg Brandl50c40002012-06-24 11:45:20 +02001598 an error to specify one of those when supplying *path* as a file descriptor.
1599
1600.. _dir_fd:
1601
Larry Hastings77892dc2012-06-25 03:27:33 -07001602* **paths relative to directory descriptors:** If *dir_fd* is not ``None``, it
Georg Brandl50c40002012-06-24 11:45:20 +02001603 should be a file descriptor referring to a directory, and the path to operate
1604 on should be relative; path will then be relative to that directory. If the
Georg Brandlaceaf902012-06-25 08:33:56 +02001605 path is absolute, *dir_fd* is ignored. (For POSIX systems, Python will call
Cheryl Sabellae1521692019-05-06 08:39:13 -04001606 the variant of the function with an ``at`` suffix and possibly prefixed with
1607 ``f`` (e.g. call ``faccessat`` instead of ``access``).
Georg Brandl50c40002012-06-24 11:45:20 +02001608
Cheryl Sabellae1521692019-05-06 08:39:13 -04001609 You can check whether or not *dir_fd* is supported for a particular function
1610 on your platform using :data:`os.supports_dir_fd`. If it's unavailable,
1611 using it will raise a :exc:`NotImplementedError`.
Georg Brandl50c40002012-06-24 11:45:20 +02001612
1613.. _follow_symlinks:
1614
Larry Hastings77892dc2012-06-25 03:27:33 -07001615* **not following symlinks:** If *follow_symlinks* is
Georg Brandl50c40002012-06-24 11:45:20 +02001616 ``False``, and the last element of the path to operate on is a symbolic link,
Cheryl Sabellae1521692019-05-06 08:39:13 -04001617 the function will operate on the symbolic link itself rather than the file
1618 pointed to by the link. (For POSIX systems, Python will call the ``l...``
1619 variant of the function.)
Georg Brandl50c40002012-06-24 11:45:20 +02001620
Cheryl Sabellae1521692019-05-06 08:39:13 -04001621 You can check whether or not *follow_symlinks* is supported for a particular
1622 function on your platform using :data:`os.supports_follow_symlinks`.
1623 If it's unavailable, using it will raise a :exc:`NotImplementedError`.
Georg Brandl50c40002012-06-24 11:45:20 +02001624
1625
1626
Larry Hastings9cf065c2012-06-22 16:30:09 -07001627.. function:: access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001628
1629 Use the real uid/gid to test for access to *path*. Note that most operations
1630 will use the effective uid/gid, therefore this routine can be used in a
1631 suid/sgid environment to test if the invoking user has the specified access to
1632 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
1633 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
1634 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
1635 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
Benjamin Petersonf650e462010-05-06 23:03:05 +00001636 information.
1637
Georg Brandl50c40002012-06-24 11:45:20 +02001638 This function can support specifying :ref:`paths relative to directory
1639 descriptors <dir_fd>` and :ref:`not following symlinks <follow_symlinks>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001640
1641 If *effective_ids* is ``True``, :func:`access` will perform its access
1642 checks using the effective uid/gid instead of the real uid/gid.
1643 *effective_ids* may not be supported on your platform; you can check whether
1644 or not it is available using :data:`os.supports_effective_ids`. If it is
1645 unavailable, using it will raise a :exc:`NotImplementedError`.
1646
Georg Brandl116aa622007-08-15 14:28:22 +00001647 .. note::
1648
Georg Brandl502d9a52009-07-26 15:02:41 +00001649 Using :func:`access` to check if a user is authorized to e.g. open a file
1650 before actually doing so using :func:`open` creates a security hole,
1651 because the user might exploit the short time interval between checking
Benjamin Peterson249b5082011-05-20 11:41:13 -05001652 and opening the file to manipulate it. It's preferable to use :term:`EAFP`
1653 techniques. For example::
1654
1655 if os.access("myfile", os.R_OK):
1656 with open("myfile") as fp:
1657 return fp.read()
1658 return "some default data"
1659
1660 is better written as::
1661
1662 try:
1663 fp = open("myfile")
Antoine Pitrou62ab10a02011-10-12 20:10:51 +02001664 except PermissionError:
1665 return "some default data"
Benjamin Peterson249b5082011-05-20 11:41:13 -05001666 else:
1667 with fp:
1668 return fp.read()
Georg Brandl116aa622007-08-15 14:28:22 +00001669
1670 .. note::
1671
1672 I/O operations may fail even when :func:`access` indicates that they would
1673 succeed, particularly for operations on network filesystems which may have
1674 permissions semantics beyond the usual POSIX permission-bit model.
1675
Larry Hastings9cf065c2012-06-22 16:30:09 -07001676 .. versionchanged:: 3.3
1677 Added the *dir_fd*, *effective_ids*, and *follow_symlinks* parameters.
1678
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001679 .. versionchanged:: 3.6
1680 Accepts a :term:`path-like object`.
1681
Georg Brandl116aa622007-08-15 14:28:22 +00001682
1683.. data:: F_OK
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001684 R_OK
1685 W_OK
1686 X_OK
Georg Brandl116aa622007-08-15 14:28:22 +00001687
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001688 Values to pass as the *mode* parameter of :func:`access` to test the
1689 existence, readability, writability and executability of *path*,
1690 respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001691
1692
1693.. function:: chdir(path)
1694
1695 .. index:: single: directory; changing
1696
Benjamin Petersonf650e462010-05-06 23:03:05 +00001697 Change the current working directory to *path*.
1698
Larry Hastings77892dc2012-06-25 03:27:33 -07001699 This function can support :ref:`specifying a file descriptor <path_fd>`. The
Georg Brandl50c40002012-06-24 11:45:20 +02001700 descriptor must refer to an opened directory, not an open file.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001701
Terry Jan Reedya9b40e42019-07-06 22:44:01 -04001702 This function can raise :exc:`OSError` and subclasses such as
Kyle Stanley0717b4d2019-07-06 21:20:15 -04001703 :exc:`FileNotFoundError`, :exc:`PermissionError`, and :exc:`NotADirectoryError`.
1704
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001705 .. audit-event:: os.chdir path os.chdir
1706
Larry Hastings9cf065c2012-06-22 16:30:09 -07001707 .. versionadded:: 3.3
1708 Added support for specifying *path* as a file descriptor
Georg Brandl50c40002012-06-24 11:45:20 +02001709 on some platforms.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001710
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001711 .. versionchanged:: 3.6
1712 Accepts a :term:`path-like object`.
1713
Georg Brandl116aa622007-08-15 14:28:22 +00001714
Larry Hastings9cf065c2012-06-22 16:30:09 -07001715.. function:: chflags(path, flags, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001716
1717 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
1718 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
1719
R David Murray30178062011-03-10 17:18:33 -05001720 * :data:`stat.UF_NODUMP`
1721 * :data:`stat.UF_IMMUTABLE`
1722 * :data:`stat.UF_APPEND`
1723 * :data:`stat.UF_OPAQUE`
1724 * :data:`stat.UF_NOUNLINK`
Ned Deily3eb67d52011-06-28 00:00:28 -07001725 * :data:`stat.UF_COMPRESSED`
1726 * :data:`stat.UF_HIDDEN`
R David Murray30178062011-03-10 17:18:33 -05001727 * :data:`stat.SF_ARCHIVED`
1728 * :data:`stat.SF_IMMUTABLE`
1729 * :data:`stat.SF_APPEND`
1730 * :data:`stat.SF_NOUNLINK`
1731 * :data:`stat.SF_SNAPSHOT`
Georg Brandl116aa622007-08-15 14:28:22 +00001732
Georg Brandl50c40002012-06-24 11:45:20 +02001733 This function can support :ref:`not following symlinks <follow_symlinks>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001734
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001735 .. audit-event:: os.chflags path,flags os.chflags
1736
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001737 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001738
Larry Hastings9cf065c2012-06-22 16:30:09 -07001739 .. versionadded:: 3.3
1740 The *follow_symlinks* argument.
1741
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001742 .. versionchanged:: 3.6
1743 Accepts a :term:`path-like object`.
1744
Georg Brandl116aa622007-08-15 14:28:22 +00001745
Larry Hastings9cf065c2012-06-22 16:30:09 -07001746.. function:: chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001747
1748 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001749 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl116aa622007-08-15 14:28:22 +00001750 combinations of them:
1751
Alexandre Vassalottic22c6f22009-07-21 00:51:58 +00001752 * :data:`stat.S_ISUID`
1753 * :data:`stat.S_ISGID`
1754 * :data:`stat.S_ENFMT`
1755 * :data:`stat.S_ISVTX`
1756 * :data:`stat.S_IREAD`
1757 * :data:`stat.S_IWRITE`
1758 * :data:`stat.S_IEXEC`
1759 * :data:`stat.S_IRWXU`
1760 * :data:`stat.S_IRUSR`
1761 * :data:`stat.S_IWUSR`
1762 * :data:`stat.S_IXUSR`
1763 * :data:`stat.S_IRWXG`
1764 * :data:`stat.S_IRGRP`
1765 * :data:`stat.S_IWGRP`
1766 * :data:`stat.S_IXGRP`
1767 * :data:`stat.S_IRWXO`
1768 * :data:`stat.S_IROTH`
1769 * :data:`stat.S_IWOTH`
1770 * :data:`stat.S_IXOTH`
Georg Brandl116aa622007-08-15 14:28:22 +00001771
Georg Brandl50c40002012-06-24 11:45:20 +02001772 This function can support :ref:`specifying a file descriptor <path_fd>`,
1773 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
1774 following symlinks <follow_symlinks>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001775
Georg Brandl116aa622007-08-15 14:28:22 +00001776 .. note::
1777
Georg Brandl50c40002012-06-24 11:45:20 +02001778 Although Windows supports :func:`chmod`, you can only set the file's
1779 read-only flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
1780 constants or a corresponding integer value). All other bits are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +00001781
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001782 .. audit-event:: os.chmod path,mode,dir_fd os.chmod
1783
Larry Hastings9cf065c2012-06-22 16:30:09 -07001784 .. versionadded:: 3.3
1785 Added support for specifying *path* as an open file descriptor,
1786 and the *dir_fd* and *follow_symlinks* arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001787
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001788 .. versionchanged:: 3.6
1789 Accepts a :term:`path-like object`.
1790
Larry Hastings9cf065c2012-06-22 16:30:09 -07001791
1792.. function:: chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001793
Georg Brandl50c40002012-06-24 11:45:20 +02001794 Change the owner and group id of *path* to the numeric *uid* and *gid*. To
1795 leave one of the ids unchanged, set it to -1.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001796
Georg Brandl50c40002012-06-24 11:45:20 +02001797 This function can support :ref:`specifying a file descriptor <path_fd>`,
1798 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
1799 following symlinks <follow_symlinks>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001800
Sandro Tosid902a142011-08-22 23:28:27 +02001801 See :func:`shutil.chown` for a higher-level function that accepts names in
1802 addition to numeric ids.
1803
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001804 .. audit-event:: os.chown path,uid,gid,dir_fd os.chown
1805
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001806 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001807
Larry Hastings9cf065c2012-06-22 16:30:09 -07001808 .. versionadded:: 3.3
Cheryl Sabellae1521692019-05-06 08:39:13 -04001809 Added support for specifying *path* as an open file descriptor,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001810 and the *dir_fd* and *follow_symlinks* arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001811
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001812 .. versionchanged:: 3.6
1813 Supports a :term:`path-like object`.
1814
Benjamin Peterson799bd802011-08-31 22:15:17 -04001815
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001816.. function:: chroot(path)
1817
Georg Brandl8a5555f2012-06-24 13:29:09 +02001818 Change the root directory of the current process to *path*.
1819
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001820 .. availability:: Unix.
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001821
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001822 .. versionchanged:: 3.6
1823 Accepts a :term:`path-like object`.
1824
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001825
1826.. function:: fchdir(fd)
1827
1828 Change the current working directory to the directory represented by the file
1829 descriptor *fd*. The descriptor must refer to an opened directory, not an
Georg Brandl4d399a42012-06-25 07:40:32 +02001830 open file. As of Python 3.3, this is equivalent to ``os.chdir(fd)``.
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001831
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001832 .. audit-event:: os.chdir path os.fchdir
1833
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001834 .. availability:: Unix.
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001835
1836
1837.. function:: getcwd()
1838
1839 Return a string representing the current working directory.
1840
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001841
1842.. function:: getcwdb()
1843
1844 Return a bytestring representing the current working directory.
1845
Victor Stinner689830e2019-06-26 17:31:12 +02001846 .. versionchanged:: 3.8
1847 The function now uses the UTF-8 encoding on Windows, rather than the ANSI
1848 code page: see :pep:`529` for the rationale. The function is no longer
1849 deprecated on Windows.
1850
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001851
Georg Brandl116aa622007-08-15 14:28:22 +00001852.. function:: lchflags(path, flags)
1853
Georg Brandl50c40002012-06-24 11:45:20 +02001854 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do
Georg Brandl4d399a42012-06-25 07:40:32 +02001855 not follow symbolic links. As of Python 3.3, this is equivalent to
Georg Brandlb9df00c2012-06-24 12:38:14 +02001856 ``os.chflags(path, flags, follow_symlinks=False)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001857
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001858 .. audit-event:: os.chflags path,flags os.lchflags
1859
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001860 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001861
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001862 .. versionchanged:: 3.6
1863 Accepts a :term:`path-like object`.
1864
Georg Brandl116aa622007-08-15 14:28:22 +00001865
Christian Heimes93852662007-12-01 12:22:32 +00001866.. function:: lchmod(path, mode)
1867
1868 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
Georg Brandl50c40002012-06-24 11:45:20 +02001869 affects the symlink rather than the target. See the docs for :func:`chmod`
Georg Brandl4d399a42012-06-25 07:40:32 +02001870 for possible values of *mode*. As of Python 3.3, this is equivalent to
Georg Brandlb9df00c2012-06-24 12:38:14 +02001871 ``os.chmod(path, mode, follow_symlinks=False)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001872
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001873 .. audit-event:: os.chmod path,mode,dir_fd os.lchmod
1874
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001875 .. availability:: Unix.
Christian Heimes93852662007-12-01 12:22:32 +00001876
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001877 .. versionchanged:: 3.6
1878 Accepts a :term:`path-like object`.
Christian Heimes93852662007-12-01 12:22:32 +00001879
Georg Brandl116aa622007-08-15 14:28:22 +00001880.. function:: lchown(path, uid, gid)
1881
Georg Brandl50c40002012-06-24 11:45:20 +02001882 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Georg Brandl4d399a42012-06-25 07:40:32 +02001883 function will not follow symbolic links. As of Python 3.3, this is equivalent
Georg Brandlb9df00c2012-06-24 12:38:14 +02001884 to ``os.chown(path, uid, gid, follow_symlinks=False)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001885
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001886 .. audit-event:: os.chown path,uid,gid,dir_fd os.lchown
1887
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001888 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001889
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001890 .. versionchanged:: 3.6
1891 Accepts a :term:`path-like object`.
1892
Georg Brandl116aa622007-08-15 14:28:22 +00001893
Larry Hastings9cf065c2012-06-22 16:30:09 -07001894.. function:: link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001895
Larry Hastings9cf065c2012-06-22 16:30:09 -07001896 Create a hard link pointing to *src* named *dst*.
Benjamin Peterson799bd802011-08-31 22:15:17 -04001897
Georg Brandlaceaf902012-06-25 08:33:56 +02001898 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
1899 supply :ref:`paths relative to directory descriptors <dir_fd>`, and :ref:`not
1900 following symlinks <follow_symlinks>`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001901
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001902 .. audit-event:: os.link src,dst,src_dir_fd,dst_dir_fd os.link
1903
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001904 .. availability:: Unix, Windows.
Brian Curtin1b9df392010-11-24 20:24:31 +00001905
1906 .. versionchanged:: 3.2
1907 Added Windows support.
Georg Brandl116aa622007-08-15 14:28:22 +00001908
Larry Hastings9cf065c2012-06-22 16:30:09 -07001909 .. versionadded:: 3.3
1910 Added the *src_dir_fd*, *dst_dir_fd*, and *follow_symlinks* arguments.
1911
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001912 .. versionchanged:: 3.6
1913 Accepts a :term:`path-like object` for *src* and *dst*.
1914
Georg Brandl116aa622007-08-15 14:28:22 +00001915
Martin v. Löwis9c71f902010-07-24 10:09:11 +00001916.. function:: listdir(path='.')
Georg Brandl116aa622007-08-15 14:28:22 +00001917
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001918 Return a list containing the names of the entries in the directory given by
Larry Hastingsfdaea062012-06-25 04:42:23 -07001919 *path*. The list is in arbitrary order, and does not include the special
1920 entries ``'.'`` and ``'..'`` even if they are present in the directory.
Serhiy Storchaka306cfb32020-09-04 21:19:30 +03001921 If a file is removed from or added to the directory during the call of
1922 this function, whether a name for that file be included is unspecified.
Georg Brandl116aa622007-08-15 14:28:22 +00001923
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001924 *path* may be a :term:`path-like object`. If *path* is of type ``bytes``
1925 (directly or indirectly through the :class:`PathLike` interface),
1926 the filenames returned will also be of type ``bytes``;
Larry Hastingsfdaea062012-06-25 04:42:23 -07001927 in all other circumstances, they will be of type ``str``.
Georg Brandl116aa622007-08-15 14:28:22 +00001928
Larry Hastings77892dc2012-06-25 03:27:33 -07001929 This function can also support :ref:`specifying a file descriptor
1930 <path_fd>`; the file descriptor must refer to a directory.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001931
Steve Dower44f91c32019-06-27 10:47:59 -07001932 .. audit-event:: os.listdir path os.listdir
Steve Dower60419a72019-06-24 08:42:54 -07001933
Larry Hastingsfdaea062012-06-25 04:42:23 -07001934 .. note::
1935 To encode ``str`` filenames to ``bytes``, use :func:`~os.fsencode`.
1936
Victor Stinner6036e442015-03-08 01:58:04 +01001937 .. seealso::
1938
Victor Stinner51b58322015-05-15 09:12:58 +02001939 The :func:`scandir` function returns directory entries along with
1940 file attribute information, giving better performance for many
1941 common use cases.
Victor Stinner6036e442015-03-08 01:58:04 +01001942
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +00001943 .. versionchanged:: 3.2
1944 The *path* parameter became optional.
Georg Brandl116aa622007-08-15 14:28:22 +00001945
Larry Hastings9cf065c2012-06-22 16:30:09 -07001946 .. versionadded:: 3.3
Cheryl Sabellae1521692019-05-06 08:39:13 -04001947 Added support for specifying *path* as an open file descriptor.
Benjamin Peterson799bd802011-08-31 22:15:17 -04001948
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001949 .. versionchanged:: 3.6
1950 Accepts a :term:`path-like object`.
1951
Georg Brandl50c40002012-06-24 11:45:20 +02001952
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02001953.. function:: lstat(path, \*, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001954
R. David Murray7b1aae92011-01-24 19:34:58 +00001955 Perform the equivalent of an :c:func:`lstat` system call on the given path.
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02001956 Similar to :func:`~os.stat`, but does not follow symbolic links. Return a
1957 :class:`stat_result` object.
1958
1959 On platforms that do not support symbolic links, this is an alias for
1960 :func:`~os.stat`.
1961
1962 As of Python 3.3, this is equivalent to ``os.stat(path, dir_fd=dir_fd,
1963 follow_symlinks=False)``.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001964
Georg Brandl50c40002012-06-24 11:45:20 +02001965 This function can also support :ref:`paths relative to directory descriptors
1966 <dir_fd>`.
Brian Curtinc7395692010-07-09 15:15:09 +00001967
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02001968 .. seealso::
1969
Berker Peksag2034caa2015-04-27 13:53:28 +03001970 The :func:`.stat` function.
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02001971
Georg Brandlb3823372010-07-10 08:58:37 +00001972 .. versionchanged:: 3.2
1973 Added support for Windows 6.0 (Vista) symbolic links.
Georg Brandl116aa622007-08-15 14:28:22 +00001974
Larry Hastings9cf065c2012-06-22 16:30:09 -07001975 .. versionchanged:: 3.3
1976 Added the *dir_fd* parameter.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001977
Brett Cannon6fa7aad2016-09-06 15:55:02 -07001978 .. versionchanged:: 3.6
1979 Accepts a :term:`path-like object` for *src* and *dst*.
1980
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001981 .. versionchanged:: 3.8
1982 On Windows, now opens reparse points that represent another path
1983 (name surrogates), including symbolic links and directory junctions.
1984 Other kinds of reparse points are resolved by the operating system as
1985 for :func:`~os.stat`.
1986
Ross Lagerwall7807c352011-03-17 20:20:30 +02001987
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001988.. function:: mkdir(path, mode=0o777, *, dir_fd=None)
1989
1990 Create a directory named *path* with numeric mode *mode*.
1991
Tommy Beadle63b91e52016-06-02 15:41:20 -04001992 If the directory already exists, :exc:`FileExistsError` is raised.
1993
1994 .. _mkdir_modebits:
1995
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001996 On some systems, *mode* is ignored. Where it is used, the current umask
Tommy Beadle63b91e52016-06-02 15:41:20 -04001997 value is first masked out. If bits other than the last 9 (i.e. the last 3
1998 digits of the octal representation of the *mode*) are set, their meaning is
1999 platform-dependent. On some platforms, they are ignored and you should call
2000 :func:`chmod` explicitly to set them.
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002001
2002 This function can also support :ref:`paths relative to directory descriptors
2003 <dir_fd>`.
2004
2005 It is also possible to create temporary directories; see the
2006 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
2007
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002008 .. audit-event:: os.mkdir path,mode,dir_fd os.mkdir
2009
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002010 .. versionadded:: 3.3
2011 The *dir_fd* argument.
2012
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002013 .. versionchanged:: 3.6
2014 Accepts a :term:`path-like object`.
2015
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002016
Zachary Warea22ae212014-03-20 09:42:01 -05002017.. function:: makedirs(name, mode=0o777, exist_ok=False)
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002018
2019 .. index::
2020 single: directory; creating
2021 single: UNC paths; and os.makedirs()
2022
2023 Recursive directory creation function. Like :func:`mkdir`, but makes all
Hynek Schlawack0230b6a2012-10-07 18:04:38 +02002024 intermediate-level directories needed to contain the leaf directory.
2025
Serhiy Storchakae304e332017-03-24 13:27:42 +02002026 The *mode* parameter is passed to :func:`mkdir` for creating the leaf
2027 directory; see :ref:`the mkdir() description <mkdir_modebits>` for how it
2028 is interpreted. To set the file permission bits of any newly-created parent
2029 directories you can set the umask before invoking :func:`makedirs`. The
2030 file permission bits of existing parent directories are not changed.
Hynek Schlawack0230b6a2012-10-07 18:04:38 +02002031
Tim Hoffmanna55f75a2019-07-05 10:41:35 +02002032 If *exist_ok* is ``False`` (the default), an :exc:`FileExistsError` is
2033 raised if the target directory already exists.
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002034
2035 .. note::
2036
2037 :func:`makedirs` will become confused if the path elements to create
Hynek Schlawack0230b6a2012-10-07 18:04:38 +02002038 include :data:`pardir` (eg. ".." on UNIX systems).
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002039
2040 This function handles UNC paths correctly.
2041
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002042 .. audit-event:: os.mkdir path,mode,dir_fd os.makedirs
2043
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002044 .. versionadded:: 3.2
2045 The *exist_ok* parameter.
2046
Benjamin Peterson1acc69c2014-04-01 19:22:06 -04002047 .. versionchanged:: 3.4.1
Benjamin Petersonee5f1c12014-04-01 19:13:18 -04002048
Benjamin Peterson1acc69c2014-04-01 19:22:06 -04002049 Before Python 3.4.1, if *exist_ok* was ``True`` and the directory existed,
Benjamin Petersonee5f1c12014-04-01 19:13:18 -04002050 :func:`makedirs` would still raise an error if *mode* did not match the
2051 mode of the existing directory. Since this behavior was impossible to
Benjamin Peterson1acc69c2014-04-01 19:22:06 -04002052 implement safely, it was removed in Python 3.4.1. See :issue:`21082`.
Benjamin Peterson4717e212014-04-01 19:17:57 -04002053
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002054 .. versionchanged:: 3.6
2055 Accepts a :term:`path-like object`.
2056
Serhiy Storchakae304e332017-03-24 13:27:42 +02002057 .. versionchanged:: 3.7
2058 The *mode* argument no longer affects the file permission bits of
2059 newly-created intermediate-level directories.
2060
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002061
Larry Hastings9cf065c2012-06-22 16:30:09 -07002062.. function:: mkfifo(path, mode=0o666, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002063
Larry Hastings9cf065c2012-06-22 16:30:09 -07002064 Create a FIFO (a named pipe) named *path* with numeric mode *mode*.
2065 The current umask value is first masked out from the mode.
2066
Georg Brandl50c40002012-06-24 11:45:20 +02002067 This function can also support :ref:`paths relative to directory descriptors
2068 <dir_fd>`.
Georg Brandl116aa622007-08-15 14:28:22 +00002069
2070 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
2071 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
2072 rendezvous between "client" and "server" type processes: the server opens the
2073 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
2074 doesn't open the FIFO --- it just creates the rendezvous point.
2075
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04002076 .. availability:: Unix.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002077
Larry Hastings9cf065c2012-06-22 16:30:09 -07002078 .. versionadded:: 3.3
2079 The *dir_fd* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00002080
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002081 .. versionchanged:: 3.6
2082 Accepts a :term:`path-like object`.
2083
Larry Hastings9cf065c2012-06-22 16:30:09 -07002084
Martin Panterbf19d162015-09-09 01:01:13 +00002085.. function:: mknod(path, mode=0o600, device=0, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002086
2087 Create a filesystem node (file, device special file or named pipe) named
Martin Panterbf19d162015-09-09 01:01:13 +00002088 *path*. *mode* specifies both the permissions to use and the type of node
Georg Brandl18244152009-09-02 20:34:52 +00002089 to be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
2090 ``stat.S_IFCHR``, ``stat.S_IFBLK``, and ``stat.S_IFIFO`` (those constants are
2091 available in :mod:`stat`). For ``stat.S_IFCHR`` and ``stat.S_IFBLK``,
2092 *device* defines the newly created device special file (probably using
Georg Brandl116aa622007-08-15 14:28:22 +00002093 :func:`os.makedev`), otherwise it is ignored.
2094
Georg Brandl50c40002012-06-24 11:45:20 +02002095 This function can also support :ref:`paths relative to directory descriptors
2096 <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002097
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04002098 .. availability:: Unix.
Berker Peksag6129e142016-09-26 22:50:11 +03002099
Larry Hastings9cf065c2012-06-22 16:30:09 -07002100 .. versionadded:: 3.3
2101 The *dir_fd* argument.
2102
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002103 .. versionchanged:: 3.6
2104 Accepts a :term:`path-like object`.
2105
Georg Brandl116aa622007-08-15 14:28:22 +00002106
2107.. function:: major(device)
2108
Christian Heimesfaf2f632008-01-06 16:59:19 +00002109 Extract the device major number from a raw device number (usually the
Georg Brandl60203b42010-10-06 10:11:56 +00002110 :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).
Georg Brandl116aa622007-08-15 14:28:22 +00002111
Georg Brandl116aa622007-08-15 14:28:22 +00002112
2113.. function:: minor(device)
2114
Christian Heimesfaf2f632008-01-06 16:59:19 +00002115 Extract the device minor number from a raw device number (usually the
Georg Brandl60203b42010-10-06 10:11:56 +00002116 :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).
Georg Brandl116aa622007-08-15 14:28:22 +00002117
Georg Brandl116aa622007-08-15 14:28:22 +00002118
2119.. function:: makedev(major, minor)
2120
Christian Heimesfaf2f632008-01-06 16:59:19 +00002121 Compose a raw device number from the major and minor device numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00002122
Georg Brandl116aa622007-08-15 14:28:22 +00002123
Georg Brandl116aa622007-08-15 14:28:22 +00002124.. function:: pathconf(path, name)
2125
2126 Return system configuration information relevant to a named file. *name*
2127 specifies the configuration value to retrieve; it may be a string which is the
2128 name of a defined system value; these names are specified in a number of
2129 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
2130 additional names as well. The names known to the host operating system are
2131 given in the ``pathconf_names`` dictionary. For configuration variables not
2132 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00002133
2134 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2135 specific value for *name* is not supported by the host system, even if it is
2136 included in ``pathconf_names``, an :exc:`OSError` is raised with
2137 :const:`errno.EINVAL` for the error number.
2138
Larry Hastings77892dc2012-06-25 03:27:33 -07002139 This function can support :ref:`specifying a file descriptor
Georg Brandl306336b2012-06-24 12:55:33 +02002140 <path_fd>`.
2141
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04002142 .. availability:: Unix.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002143
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002144 .. versionchanged:: 3.6
2145 Accepts a :term:`path-like object`.
2146
Georg Brandl116aa622007-08-15 14:28:22 +00002147
2148.. data:: pathconf_names
2149
2150 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
2151 the integer values defined for those names by the host operating system. This
Georg Brandl8a5555f2012-06-24 13:29:09 +02002152 can be used to determine the set of names known to the system.
2153
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04002154 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002155
2156
Larry Hastings9cf065c2012-06-22 16:30:09 -07002157.. function:: readlink(path, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002158
2159 Return a string representing the path to which the symbolic link points. The
Georg Brandl50c40002012-06-24 11:45:20 +02002160 result may be either an absolute or relative pathname; if it is relative, it
2161 may be converted to an absolute pathname using
2162 ``os.path.join(os.path.dirname(path), result)``.
Georg Brandl116aa622007-08-15 14:28:22 +00002163
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002164 If the *path* is a string object (directly or indirectly through a
2165 :class:`PathLike` interface), the result will also be a string object,
Martin Panter6245cb32016-04-15 02:14:19 +00002166 and the call may raise a UnicodeDecodeError. If the *path* is a bytes
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002167 object (direct or indirectly), the result will be a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +00002168
Georg Brandl50c40002012-06-24 11:45:20 +02002169 This function can also support :ref:`paths relative to directory descriptors
2170 <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002171
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002172 When trying to resolve a path that may contain links, use
2173 :func:`~os.path.realpath` to properly handle recursion and platform
2174 differences.
2175
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04002176 .. availability:: Unix, Windows.
Brian Curtinc7395692010-07-09 15:15:09 +00002177
Georg Brandlb3823372010-07-10 08:58:37 +00002178 .. versionchanged:: 3.2
2179 Added support for Windows 6.0 (Vista) symbolic links.
Georg Brandl116aa622007-08-15 14:28:22 +00002180
Larry Hastings9cf065c2012-06-22 16:30:09 -07002181 .. versionadded:: 3.3
2182 The *dir_fd* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00002183
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002184 .. versionchanged:: 3.6
Berker Peksage0b5b202018-08-15 13:03:41 +03002185 Accepts a :term:`path-like object` on Unix.
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002186
Berker Peksage0b5b202018-08-15 13:03:41 +03002187 .. versionchanged:: 3.8
2188 Accepts a :term:`path-like object` and a bytes object on Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002189
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002190 .. versionchanged:: 3.8
2191 Added support for directory junctions, and changed to return the
2192 substitution path (which typically includes ``\\?\`` prefix) rather
2193 than the optional "print name" field that was previously returned.
2194
Larry Hastingsb698d8e2012-06-23 16:55:07 -07002195.. function:: remove(path, *, dir_fd=None)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002196
Tim Hoffmanna55f75a2019-07-05 10:41:35 +02002197 Remove (delete) the file *path*. If *path* is a directory, an
2198 :exc:`IsADirectoryError` is raised. Use :func:`rmdir` to remove directories.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002199
Georg Brandl50c40002012-06-24 11:45:20 +02002200 This function can support :ref:`paths relative to directory descriptors
2201 <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002202
2203 On Windows, attempting to remove a file that is in use causes an exception to
2204 be raised; on Unix, the directory entry is removed but the storage allocated
2205 to the file is not made available until the original file is no longer in use.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002206
Brett Cannon05039172015-12-28 17:28:19 -08002207 This function is semantically identical to :func:`unlink`.
Larry Hastingsb698d8e2012-06-23 16:55:07 -07002208
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002209 .. audit-event:: os.remove path,dir_fd os.remove
2210
Larry Hastings9cf065c2012-06-22 16:30:09 -07002211 .. versionadded:: 3.3
Larry Hastingsb698d8e2012-06-23 16:55:07 -07002212 The *dir_fd* argument.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002213
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002214 .. versionchanged:: 3.6
2215 Accepts a :term:`path-like object`.
2216
Georg Brandl116aa622007-08-15 14:28:22 +00002217
Zachary Warea22ae212014-03-20 09:42:01 -05002218.. function:: removedirs(name)
Georg Brandl116aa622007-08-15 14:28:22 +00002219
2220 .. index:: single: directory; deleting
2221
Christian Heimesfaf2f632008-01-06 16:59:19 +00002222 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl116aa622007-08-15 14:28:22 +00002223 leaf directory is successfully removed, :func:`removedirs` tries to
2224 successively remove every parent directory mentioned in *path* until an error
2225 is raised (which is ignored, because it generally means that a parent directory
2226 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
2227 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
2228 they are empty. Raises :exc:`OSError` if the leaf directory could not be
2229 successfully removed.
2230
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002231 .. audit-event:: os.remove path,dir_fd os.removedirs
2232
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002233 .. versionchanged:: 3.6
2234 Accepts a :term:`path-like object`.
2235
Georg Brandl116aa622007-08-15 14:28:22 +00002236
Larry Hastings9cf065c2012-06-22 16:30:09 -07002237.. function:: rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002238
Tim Hoffmanna55f75a2019-07-05 10:41:35 +02002239 Rename the file or directory *src* to *dst*. If *dst* exists, the operation
2240 will fail with an :exc:`OSError` subclass in a number of cases:
2241
2242 On Windows, if *dst* exists a :exc:`FileExistsError` is always raised.
2243
Mariatta7cbef722019-07-11 10:31:19 -07002244 On Unix, if *src* is a file and *dst* is a directory or vice-versa, an
Tim Hoffmanna55f75a2019-07-05 10:41:35 +02002245 :exc:`IsADirectoryError` or a :exc:`NotADirectoryError` will be raised
2246 respectively. If both are directories and *dst* is empty, *dst* will be
2247 silently replaced. If *dst* is a non-empty directory, an :exc:`OSError`
2248 is raised. If both are files, *dst* it will be replaced silently if the user
2249 has permission. The operation may fail on some Unix flavors if *src* and
2250 *dst* are on different filesystems. If successful, the renaming will be an
2251 atomic operation (this is a POSIX requirement).
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01002252
Georg Brandlaceaf902012-06-25 08:33:56 +02002253 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
2254 supply :ref:`paths relative to directory descriptors <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002255
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01002256 If you want cross-platform overwriting of the destination, use :func:`replace`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002257
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002258 .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.rename
2259
Larry Hastings9cf065c2012-06-22 16:30:09 -07002260 .. versionadded:: 3.3
2261 The *src_dir_fd* and *dst_dir_fd* arguments.
2262
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002263 .. versionchanged:: 3.6
2264 Accepts a :term:`path-like object` for *src* and *dst*.
2265
Georg Brandl116aa622007-08-15 14:28:22 +00002266
2267.. function:: renames(old, new)
2268
2269 Recursive directory or file renaming function. Works like :func:`rename`, except
2270 creation of any intermediate directories needed to make the new pathname good is
2271 attempted first. After the rename, directories corresponding to rightmost path
2272 segments of the old name will be pruned away using :func:`removedirs`.
2273
Georg Brandl116aa622007-08-15 14:28:22 +00002274 .. note::
2275
2276 This function can fail with the new directory structure made if you lack
2277 permissions needed to remove the leaf directory or file.
2278
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002279 .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.renames
2280
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002281 .. versionchanged:: 3.6
2282 Accepts a :term:`path-like object` for *old* and *new*.
2283
Georg Brandl116aa622007-08-15 14:28:22 +00002284
Larry Hastings9cf065c2012-06-22 16:30:09 -07002285.. function:: replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01002286
2287 Rename the file or directory *src* to *dst*. If *dst* is a directory,
2288 :exc:`OSError` will be raised. If *dst* exists and is a file, it will
2289 be replaced silently if the user has permission. The operation may fail
2290 if *src* and *dst* are on different filesystems. If successful,
2291 the renaming will be an atomic operation (this is a POSIX requirement).
2292
Georg Brandlaceaf902012-06-25 08:33:56 +02002293 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
2294 supply :ref:`paths relative to directory descriptors <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002295
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002296 .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.replace
2297
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01002298 .. versionadded:: 3.3
2299
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002300 .. versionchanged:: 3.6
2301 Accepts a :term:`path-like object` for *src* and *dst*.
2302
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01002303
Larry Hastingsb698d8e2012-06-23 16:55:07 -07002304.. function:: rmdir(path, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002305
Tim Hoffmanna55f75a2019-07-05 10:41:35 +02002306 Remove (delete) the directory *path*. If the directory does not exist or is
2307 not empty, an :exc:`FileNotFoundError` or an :exc:`OSError` is raised
2308 respectively. In order to remove whole directory trees,
2309 :func:`shutil.rmtree` can be used.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002310
Georg Brandl50c40002012-06-24 11:45:20 +02002311 This function can support :ref:`paths relative to directory descriptors
2312 <dir_fd>`.
Larry Hastingsb698d8e2012-06-23 16:55:07 -07002313
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002314 .. audit-event:: os.rmdir path,dir_fd os.rmdir
2315
Larry Hastingsb698d8e2012-06-23 16:55:07 -07002316 .. versionadded:: 3.3
2317 The *dir_fd* parameter.
2318
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002319 .. versionchanged:: 3.6
2320 Accepts a :term:`path-like object`.
2321
Georg Brandl116aa622007-08-15 14:28:22 +00002322
Victor Stinner6036e442015-03-08 01:58:04 +01002323.. function:: scandir(path='.')
2324
Brett Cannona32c4d02016-06-24 14:14:44 -07002325 Return an iterator of :class:`os.DirEntry` objects corresponding to the
2326 entries in the directory given by *path*. The entries are yielded in
2327 arbitrary order, and the special entries ``'.'`` and ``'..'`` are not
Serhiy Storchaka306cfb32020-09-04 21:19:30 +03002328 included. If a file is removed from or added to the directory after
2329 creating the iterator, whether an entry for that file be included is
2330 unspecified.
Victor Stinner6036e442015-03-08 01:58:04 +01002331
Victor Stinner51b58322015-05-15 09:12:58 +02002332 Using :func:`scandir` instead of :func:`listdir` can significantly
2333 increase the performance of code that also needs file type or file
Brett Cannona32c4d02016-06-24 14:14:44 -07002334 attribute information, because :class:`os.DirEntry` objects expose this
Victor Stinner51b58322015-05-15 09:12:58 +02002335 information if the operating system provides it when scanning a directory.
Brett Cannona32c4d02016-06-24 14:14:44 -07002336 All :class:`os.DirEntry` methods may perform a system call, but
2337 :func:`~os.DirEntry.is_dir` and :func:`~os.DirEntry.is_file` usually only
2338 require a system call for symbolic links; :func:`os.DirEntry.stat`
Victor Stinner51b58322015-05-15 09:12:58 +02002339 always requires a system call on Unix but only requires one for
2340 symbolic links on Windows.
Victor Stinner6036e442015-03-08 01:58:04 +01002341
Serhiy Storchaka3c38e062016-11-20 08:23:07 +02002342 *path* may be a :term:`path-like object`. If *path* is of type ``bytes``
2343 (directly or indirectly through the :class:`PathLike` interface),
2344 the type of the :attr:`~os.DirEntry.name` and :attr:`~os.DirEntry.path`
2345 attributes of each :class:`os.DirEntry` will be ``bytes``; in all other
2346 circumstances, they will be of type ``str``.
Victor Stinner6036e442015-03-08 01:58:04 +01002347
Serhiy Storchakaea720fe2017-03-30 09:12:31 +03002348 This function can also support :ref:`specifying a file descriptor
2349 <path_fd>`; the file descriptor must refer to a directory.
2350
Steve Dower44f91c32019-06-27 10:47:59 -07002351 .. audit-event:: os.scandir path os.scandir
Steve Dower60419a72019-06-24 08:42:54 -07002352
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +02002353 The :func:`scandir` iterator supports the :term:`context manager` protocol
2354 and has the following method:
2355
2356 .. method:: scandir.close()
2357
2358 Close the iterator and free acquired resources.
2359
2360 This is called automatically when the iterator is exhausted or garbage
2361 collected, or when an error happens during iterating. However it
2362 is advisable to call it explicitly or use the :keyword:`with`
2363 statement.
2364
2365 .. versionadded:: 3.6
2366
Victor Stinner6036e442015-03-08 01:58:04 +01002367 The following example shows a simple use of :func:`scandir` to display all
Victor Stinner51b58322015-05-15 09:12:58 +02002368 the files (excluding directories) in the given *path* that don't start with
2369 ``'.'``. The ``entry.is_file()`` call will generally not make an additional
2370 system call::
Victor Stinner6036e442015-03-08 01:58:04 +01002371
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +02002372 with os.scandir(path) as it:
2373 for entry in it:
2374 if not entry.name.startswith('.') and entry.is_file():
2375 print(entry.name)
Victor Stinner6036e442015-03-08 01:58:04 +01002376
2377 .. note::
2378
2379 On Unix-based systems, :func:`scandir` uses the system's
2380 `opendir() <http://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html>`_
2381 and
2382 `readdir() <http://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html>`_
2383 functions. On Windows, it uses the Win32
Georg Brandl5d941342016-02-26 19:37:12 +01002384 `FindFirstFileW <https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx>`_
Victor Stinner6036e442015-03-08 01:58:04 +01002385 and
Georg Brandl5d941342016-02-26 19:37:12 +01002386 `FindNextFileW <https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx>`_
Victor Stinner6036e442015-03-08 01:58:04 +01002387 functions.
2388
Victor Stinner6036e442015-03-08 01:58:04 +01002389 .. versionadded:: 3.5
2390
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +02002391 .. versionadded:: 3.6
2392 Added support for the :term:`context manager` protocol and the
2393 :func:`~scandir.close()` method. If a :func:`scandir` iterator is neither
2394 exhausted nor explicitly closed a :exc:`ResourceWarning` will be emitted
2395 in its destructor.
2396
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002397 The function accepts a :term:`path-like object`.
2398
Serhiy Storchakaea720fe2017-03-30 09:12:31 +03002399 .. versionchanged:: 3.7
2400 Added support for :ref:`file descriptors <path_fd>` on Unix.
2401
Victor Stinner6036e442015-03-08 01:58:04 +01002402
2403.. class:: DirEntry
2404
2405 Object yielded by :func:`scandir` to expose the file path and other file
2406 attributes of a directory entry.
2407
2408 :func:`scandir` will provide as much of this information as possible without
2409 making additional system calls. When a ``stat()`` or ``lstat()`` system call
Brett Cannona32c4d02016-06-24 14:14:44 -07002410 is made, the ``os.DirEntry`` object will cache the result.
Victor Stinner6036e442015-03-08 01:58:04 +01002411
Brett Cannona32c4d02016-06-24 14:14:44 -07002412 ``os.DirEntry`` instances are not intended to be stored in long-lived data
Victor Stinner6036e442015-03-08 01:58:04 +01002413 structures; if you know the file metadata has changed or if a long time has
2414 elapsed since calling :func:`scandir`, call ``os.stat(entry.path)`` to fetch
2415 up-to-date information.
2416
Brett Cannona32c4d02016-06-24 14:14:44 -07002417 Because the ``os.DirEntry`` methods can make operating system calls, they may
Victor Stinner51b58322015-05-15 09:12:58 +02002418 also raise :exc:`OSError`. If you need very fine-grained
Victor Stinner6036e442015-03-08 01:58:04 +01002419 control over errors, you can catch :exc:`OSError` when calling one of the
Brett Cannona32c4d02016-06-24 14:14:44 -07002420 ``os.DirEntry`` methods and handle as appropriate.
Victor Stinner6036e442015-03-08 01:58:04 +01002421
Brett Cannona32c4d02016-06-24 14:14:44 -07002422 To be directly usable as a :term:`path-like object`, ``os.DirEntry``
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002423 implements the :class:`PathLike` interface.
Brett Cannon96881cd2016-06-10 14:37:21 -07002424
Brett Cannona32c4d02016-06-24 14:14:44 -07002425 Attributes and methods on a ``os.DirEntry`` instance are as follows:
Victor Stinner6036e442015-03-08 01:58:04 +01002426
2427 .. attribute:: name
2428
2429 The entry's base filename, relative to the :func:`scandir` *path*
2430 argument.
2431
Serhiy Storchaka3c38e062016-11-20 08:23:07 +02002432 The :attr:`name` attribute will be ``bytes`` if the :func:`scandir`
2433 *path* argument is of type ``bytes`` and ``str`` otherwise. Use
Victor Stinner51b58322015-05-15 09:12:58 +02002434 :func:`~os.fsdecode` to decode byte filenames.
Victor Stinner6036e442015-03-08 01:58:04 +01002435
2436 .. attribute:: path
2437
2438 The entry's full path name: equivalent to ``os.path.join(scandir_path,
2439 entry.name)`` where *scandir_path* is the :func:`scandir` *path*
2440 argument. The path is only absolute if the :func:`scandir` *path*
Serhiy Storchakaea720fe2017-03-30 09:12:31 +03002441 argument was absolute. If the :func:`scandir` *path*
2442 argument was a :ref:`file descriptor <path_fd>`, the :attr:`path`
2443 attribute is the same as the :attr:`name` attribute.
Victor Stinner6036e442015-03-08 01:58:04 +01002444
Serhiy Storchaka3c38e062016-11-20 08:23:07 +02002445 The :attr:`path` attribute will be ``bytes`` if the :func:`scandir`
2446 *path* argument is of type ``bytes`` and ``str`` otherwise. Use
Victor Stinner51b58322015-05-15 09:12:58 +02002447 :func:`~os.fsdecode` to decode byte filenames.
Victor Stinner6036e442015-03-08 01:58:04 +01002448
2449 .. method:: inode()
2450
2451 Return the inode number of the entry.
2452
Brett Cannona32c4d02016-06-24 14:14:44 -07002453 The result is cached on the ``os.DirEntry`` object. Use
2454 ``os.stat(entry.path, follow_symlinks=False).st_ino`` to fetch up-to-date
2455 information.
Victor Stinner6036e442015-03-08 01:58:04 +01002456
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002457 On the first, uncached call, a system call is required on Windows but
2458 not on Unix.
Victor Stinner6036e442015-03-08 01:58:04 +01002459
2460 .. method:: is_dir(\*, follow_symlinks=True)
2461
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002462 Return ``True`` if this entry is a directory or a symbolic link pointing
2463 to a directory; return ``False`` if the entry is or points to any other
2464 kind of file, or if it doesn't exist anymore.
Victor Stinner6036e442015-03-08 01:58:04 +01002465
2466 If *follow_symlinks* is ``False``, return ``True`` only if this entry
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002467 is a directory (without following symlinks); return ``False`` if the
2468 entry is any other kind of file or if it doesn't exist anymore.
Victor Stinner6036e442015-03-08 01:58:04 +01002469
Brett Cannona32c4d02016-06-24 14:14:44 -07002470 The result is cached on the ``os.DirEntry`` object, with a separate cache
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002471 for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` along
2472 with :func:`stat.S_ISDIR` to fetch up-to-date information.
2473
2474 On the first, uncached call, no system call is required in most cases.
2475 Specifically, for non-symlinks, neither Windows or Unix require a system
2476 call, except on certain Unix file systems, such as network file systems,
2477 that return ``dirent.d_type == DT_UNKNOWN``. If the entry is a symlink,
2478 a system call will be required to follow the symlink unless
2479 *follow_symlinks* is ``False``.
Victor Stinner6036e442015-03-08 01:58:04 +01002480
Victor Stinner51b58322015-05-15 09:12:58 +02002481 This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2482 but :exc:`FileNotFoundError` is caught and not raised.
Victor Stinner6036e442015-03-08 01:58:04 +01002483
Victor Stinner6036e442015-03-08 01:58:04 +01002484 .. method:: is_file(\*, follow_symlinks=True)
2485
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002486 Return ``True`` if this entry is a file or a symbolic link pointing to a
2487 file; return ``False`` if the entry is or points to a directory or other
2488 non-file entry, or if it doesn't exist anymore.
Victor Stinner6036e442015-03-08 01:58:04 +01002489
2490 If *follow_symlinks* is ``False``, return ``True`` only if this entry
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002491 is a file (without following symlinks); return ``False`` if the entry is
2492 a directory or other non-file entry, or if it doesn't exist anymore.
Victor Stinner6036e442015-03-08 01:58:04 +01002493
Brett Cannona32c4d02016-06-24 14:14:44 -07002494 The result is cached on the ``os.DirEntry`` object. Caching, system calls
2495 made, and exceptions raised are as per :func:`~os.DirEntry.is_dir`.
Victor Stinner6036e442015-03-08 01:58:04 +01002496
2497 .. method:: is_symlink()
2498
Victor Stinner51b58322015-05-15 09:12:58 +02002499 Return ``True`` if this entry is a symbolic link (even if broken);
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002500 return ``False`` if the entry points to a directory or any kind of file,
Victor Stinner51b58322015-05-15 09:12:58 +02002501 or if it doesn't exist anymore.
Victor Stinner6036e442015-03-08 01:58:04 +01002502
Brett Cannona32c4d02016-06-24 14:14:44 -07002503 The result is cached on the ``os.DirEntry`` object. Call
Victor Stinner51b58322015-05-15 09:12:58 +02002504 :func:`os.path.islink` to fetch up-to-date information.
Victor Stinner6036e442015-03-08 01:58:04 +01002505
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002506 On the first, uncached call, no system call is required in most cases.
2507 Specifically, neither Windows or Unix require a system call, except on
2508 certain Unix file systems, such as network file systems, that return
2509 ``dirent.d_type == DT_UNKNOWN``.
Victor Stinner6036e442015-03-08 01:58:04 +01002510
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002511 This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2512 but :exc:`FileNotFoundError` is caught and not raised.
Victor Stinner6036e442015-03-08 01:58:04 +01002513
2514 .. method:: stat(\*, follow_symlinks=True)
2515
Victor Stinner51b58322015-05-15 09:12:58 +02002516 Return a :class:`stat_result` object for this entry. This method
2517 follows symbolic links by default; to stat a symbolic link add the
2518 ``follow_symlinks=False`` argument.
2519
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002520 On Unix, this method always requires a system call. On Windows, it
2521 only requires a system call if *follow_symlinks* is ``True`` and the
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002522 entry is a reparse point (for example, a symbolic link or directory
2523 junction).
Victor Stinner6036e442015-03-08 01:58:04 +01002524
2525 On Windows, the ``st_ino``, ``st_dev`` and ``st_nlink`` attributes of the
2526 :class:`stat_result` are always set to zero. Call :func:`os.stat` to
2527 get these attributes.
2528
Brett Cannona32c4d02016-06-24 14:14:44 -07002529 The result is cached on the ``os.DirEntry`` object, with a separate cache
Victor Stinner5f0c5d92016-01-31 18:36:41 +01002530 for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` to
2531 fetch up-to-date information.
Victor Stinner6036e442015-03-08 01:58:04 +01002532
Guido van Rossum1469d742016-01-06 11:36:03 -08002533 Note that there is a nice correspondence between several attributes
Brett Cannona32c4d02016-06-24 14:14:44 -07002534 and methods of ``os.DirEntry`` and of :class:`pathlib.Path`. In
Brett Cannonc28592b2016-06-24 12:21:47 -07002535 particular, the ``name`` attribute has the same
Guido van Rossum1469d742016-01-06 11:36:03 -08002536 meaning, as do the ``is_dir()``, ``is_file()``, ``is_symlink()``
2537 and ``stat()`` methods.
2538
Victor Stinner6036e442015-03-08 01:58:04 +01002539 .. versionadded:: 3.5
2540
Brett Cannon96881cd2016-06-10 14:37:21 -07002541 .. versionchanged:: 3.6
Serhiy Storchaka3c38e062016-11-20 08:23:07 +02002542 Added support for the :class:`~os.PathLike` interface. Added support
2543 for :class:`bytes` paths on Windows.
Brett Cannon96881cd2016-06-10 14:37:21 -07002544
Victor Stinner6036e442015-03-08 01:58:04 +01002545
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002546.. function:: stat(path, \*, dir_fd=None, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00002547
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002548 Get the status of a file or a file descriptor. Perform the equivalent of a
2549 :c:func:`stat` system call on the given path. *path* may be specified as
Xiang Zhang4459e002017-01-22 13:04:17 +08002550 either a string or bytes -- directly or indirectly through the :class:`PathLike`
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002551 interface -- or as an open file descriptor. Return a :class:`stat_result`
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002552 object.
Georg Brandl116aa622007-08-15 14:28:22 +00002553
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002554 This function normally follows symlinks; to stat a symlink add the argument
2555 ``follow_symlinks=False``, or use :func:`lstat`.
R. David Murray7b1aae92011-01-24 19:34:58 +00002556
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002557 This function can support :ref:`specifying a file descriptor <path_fd>` and
2558 :ref:`not following symlinks <follow_symlinks>`.
Georg Brandl116aa622007-08-15 14:28:22 +00002559
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002560 On Windows, passing ``follow_symlinks=False`` will disable following all
2561 name-surrogate reparse points, which includes symlinks and directory
2562 junctions. Other types of reparse points that do not resemble links or that
2563 the operating system is unable to follow will be opened directly. When
2564 following a chain of multiple links, this may result in the original link
2565 being returned instead of the non-link that prevented full traversal. To
2566 obtain stat results for the final path in this case, use the
2567 :func:`os.path.realpath` function to resolve the path name as far as
2568 possible and call :func:`lstat` on the result. This does not apply to
2569 dangling symlinks or junction points, which will raise the usual exceptions.
2570
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002571 .. index:: module: stat
R. David Murray7b1aae92011-01-24 19:34:58 +00002572
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002573 Example::
Georg Brandl116aa622007-08-15 14:28:22 +00002574
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002575 >>> import os
2576 >>> statinfo = os.stat('somefile.txt')
2577 >>> statinfo
2578 os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
2579 st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
2580 st_mtime=1297230027, st_ctime=1297230027)
2581 >>> statinfo.st_size
2582 264
R. David Murray7b1aae92011-01-24 19:34:58 +00002583
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002584 .. seealso::
Zachary Ware63f277b2014-06-19 09:46:37 -05002585
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002586 :func:`fstat` and :func:`lstat` functions.
2587
2588 .. versionadded:: 3.3
2589 Added the *dir_fd* and *follow_symlinks* arguments, specifying a file
2590 descriptor instead of a path.
2591
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002592 .. versionchanged:: 3.6
2593 Accepts a :term:`path-like object`.
2594
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002595 .. versionchanged:: 3.8
2596 On Windows, all reparse points that can be resolved by the operating
2597 system are now followed, and passing ``follow_symlinks=False``
2598 disables following all name surrogate reparse points. If the operating
2599 system reaches a reparse point that it is not able to follow, *stat* now
2600 returns the information for the original path as if
2601 ``follow_symlinks=False`` had been specified instead of raising an error.
2602
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002603
2604.. class:: stat_result
2605
2606 Object whose attributes correspond roughly to the members of the
2607 :c:type:`stat` structure. It is used for the result of :func:`os.stat`,
2608 :func:`os.fstat` and :func:`os.lstat`.
2609
2610 Attributes:
2611
2612 .. attribute:: st_mode
2613
2614 File mode: file type and file mode bits (permissions).
2615
2616 .. attribute:: st_ino
2617
Steve Dower3e51a3d2018-05-28 17:24:36 -07002618 Platform dependent, but if non-zero, uniquely identifies the
2619 file for a given value of ``st_dev``. Typically:
2620
2621 * the inode number on Unix,
2622 * the `file index
2623 <https://msdn.microsoft.com/en-us/library/aa363788>`_ on
2624 Windows
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002625
2626 .. attribute:: st_dev
2627
2628 Identifier of the device on which this file resides.
2629
2630 .. attribute:: st_nlink
2631
2632 Number of hard links.
2633
2634 .. attribute:: st_uid
2635
2636 User identifier of the file owner.
2637
2638 .. attribute:: st_gid
2639
2640 Group identifier of the file owner.
2641
2642 .. attribute:: st_size
2643
2644 Size of the file in bytes, if it is a regular file or a symbolic link.
2645 The size of a symbolic link is the length of the pathname it contains,
2646 without a terminating null byte.
2647
2648 Timestamps:
2649
2650 .. attribute:: st_atime
2651
2652 Time of most recent access expressed in seconds.
2653
2654 .. attribute:: st_mtime
2655
2656 Time of most recent content modification expressed in seconds.
2657
2658 .. attribute:: st_ctime
2659
2660 Platform dependent:
2661
2662 * the time of most recent metadata change on Unix,
2663 * the time of creation on Windows, expressed in seconds.
2664
2665 .. attribute:: st_atime_ns
2666
2667 Time of most recent access expressed in nanoseconds as an integer.
2668
2669 .. attribute:: st_mtime_ns
2670
2671 Time of most recent content modification expressed in nanoseconds as an
2672 integer.
2673
2674 .. attribute:: st_ctime_ns
2675
2676 Platform dependent:
2677
2678 * the time of most recent metadata change on Unix,
2679 * the time of creation on Windows, expressed in nanoseconds as an
2680 integer.
2681
Georg Brandl116aa622007-08-15 14:28:22 +00002682 .. note::
2683
Senthil Kumaran3aac1792011-07-04 11:43:51 -07002684 The exact meaning and resolution of the :attr:`st_atime`,
Senthil Kumarana6bac952011-07-04 11:28:30 -07002685 :attr:`st_mtime`, and :attr:`st_ctime` attributes depend on the operating
2686 system and the file system. For example, on Windows systems using the FAT
2687 or FAT32 file systems, :attr:`st_mtime` has 2-second resolution, and
2688 :attr:`st_atime` has only 1-day resolution. See your operating system
2689 documentation for details.
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002690
Larry Hastings6fe20b32012-04-19 15:07:49 -07002691 Similarly, although :attr:`st_atime_ns`, :attr:`st_mtime_ns`,
2692 and :attr:`st_ctime_ns` are always expressed in nanoseconds, many
2693 systems do not provide nanosecond precision. On systems that do
2694 provide nanosecond precision, the floating-point object used to
2695 store :attr:`st_atime`, :attr:`st_mtime`, and :attr:`st_ctime`
2696 cannot preserve all of it, and as such will be slightly inexact.
2697 If you need the exact timestamps you should always use
2698 :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and :attr:`st_ctime_ns`.
Georg Brandl116aa622007-08-15 14:28:22 +00002699
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002700 On some Unix systems (such as Linux), the following attributes may also be
2701 available:
2702
2703 .. attribute:: st_blocks
2704
2705 Number of 512-byte blocks allocated for file.
2706 This may be smaller than :attr:`st_size`/512 when the file has holes.
2707
2708 .. attribute:: st_blksize
2709
2710 "Preferred" blocksize for efficient file system I/O. Writing to a file in
2711 smaller chunks may cause an inefficient read-modify-rewrite.
2712
2713 .. attribute:: st_rdev
2714
2715 Type of device if an inode device.
2716
2717 .. attribute:: st_flags
2718
2719 User defined flags for file.
2720
2721 On other Unix systems (such as FreeBSD), the following attributes may be
2722 available (but may be only filled out if root tries to use them):
2723
2724 .. attribute:: st_gen
2725
2726 File generation number.
2727
2728 .. attribute:: st_birthtime
2729
2730 Time of file creation.
2731
jcea6c51d512018-01-28 14:00:08 +01002732 On Solaris and derivatives, the following attributes may also be
2733 available:
2734
2735 .. attribute:: st_fstype
2736
2737 String that uniquely identifies the type of the filesystem that
2738 contains the file.
2739
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002740 On Mac OS systems, the following attributes may also be available:
2741
2742 .. attribute:: st_rsize
2743
2744 Real size of the file.
2745
2746 .. attribute:: st_creator
2747
2748 Creator of the file.
2749
2750 .. attribute:: st_type
2751
2752 File type.
2753
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002754 On Windows systems, the following attributes are also available:
Victor Stinnere1d24f72014-07-24 12:44:07 +02002755
2756 .. attribute:: st_file_attributes
2757
2758 Windows file attributes: ``dwFileAttributes`` member of the
2759 ``BY_HANDLE_FILE_INFORMATION`` structure returned by
2760 :c:func:`GetFileInformationByHandle`. See the ``FILE_ATTRIBUTE_*``
2761 constants in the :mod:`stat` module.
2762
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002763 .. attribute:: st_reparse_tag
2764
2765 When :attr:`st_file_attributes` has the ``FILE_ATTRIBUTE_REPARSE_POINT``
2766 set, this field contains the tag identifying the type of reparse point.
2767 See the ``IO_REPARSE_TAG_*`` constants in the :mod:`stat` module.
2768
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002769 The standard module :mod:`stat` defines functions and constants that are
2770 useful for extracting information from a :c:type:`stat` structure. (On
2771 Windows, some items are filled with dummy values.)
2772
2773 For backward compatibility, a :class:`stat_result` instance is also
Georg Brandl50c40002012-06-24 11:45:20 +02002774 accessible as a tuple of at least 10 integers giving the most important (and
2775 portable) members of the :c:type:`stat` structure, in the order
2776 :attr:`st_mode`, :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`,
2777 :attr:`st_uid`, :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`,
2778 :attr:`st_mtime`, :attr:`st_ctime`. More items may be added at the end by
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002779 some implementations. For compatibility with older Python versions,
2780 accessing :class:`stat_result` as a tuple always returns integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002781
Larry Hastings6fe20b32012-04-19 15:07:49 -07002782 .. versionadded:: 3.3
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002783 Added the :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and
2784 :attr:`st_ctime_ns` members.
Larry Hastings6fe20b32012-04-19 15:07:49 -07002785
Zachary Ware63f277b2014-06-19 09:46:37 -05002786 .. versionadded:: 3.5
2787 Added the :attr:`st_file_attributes` member on Windows.
2788
Steve Dower3e51a3d2018-05-28 17:24:36 -07002789 .. versionchanged:: 3.5
2790 Windows now returns the file index as :attr:`st_ino` when
2791 available.
2792
jcea6c51d512018-01-28 14:00:08 +01002793 .. versionadded:: 3.7
2794 Added the :attr:`st_fstype` member to Solaris/derivatives.
Georg Brandl116aa622007-08-15 14:28:22 +00002795
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002796 .. versionadded:: 3.8
2797 Added the :attr:`st_reparse_tag` member on Windows.
2798
2799 .. versionchanged:: 3.8
2800 On Windows, the :attr:`st_mode` member now identifies special
2801 files as :const:`S_IFCHR`, :const:`S_IFIFO` or :const:`S_IFBLK`
2802 as appropriate.
2803
Georg Brandl116aa622007-08-15 14:28:22 +00002804.. function:: statvfs(path)
2805
Georg Brandl60203b42010-10-06 10:11:56 +00002806 Perform a :c:func:`statvfs` system call on the given path. The return value is
Georg Brandl116aa622007-08-15 14:28:22 +00002807 an object whose attributes describe the filesystem on the given path, and
Georg Brandl60203b42010-10-06 10:11:56 +00002808 correspond to the members of the :c:type:`statvfs` structure, namely:
Georg Brandl116aa622007-08-15 14:28:22 +00002809 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
2810 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002811 :attr:`f_flag`, :attr:`f_namemax`, :attr:`f_fsid`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002812
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +00002813 Two module-level constants are defined for the :attr:`f_flag` attribute's
2814 bit-flags: if :const:`ST_RDONLY` is set, the filesystem is mounted
2815 read-only, and if :const:`ST_NOSUID` is set, the semantics of
2816 setuid/setgid bits are disabled or not supported.
2817
doko@ubuntu.comca616a22013-12-08 15:23:07 +01002818 Additional module-level constants are defined for GNU/glibc based systems.
2819 These are :const:`ST_NODEV` (disallow access to device special files),
2820 :const:`ST_NOEXEC` (disallow program execution), :const:`ST_SYNCHRONOUS`
2821 (writes are synced at once), :const:`ST_MANDLOCK` (allow mandatory locks on an FS),
2822 :const:`ST_WRITE` (write on file/directory/symlink), :const:`ST_APPEND`
2823 (append-only file), :const:`ST_IMMUTABLE` (immutable file), :const:`ST_NOATIME`
2824 (do not update access times), :const:`ST_NODIRATIME` (do not update directory access
2825 times), :const:`ST_RELATIME` (update atime relative to mtime/ctime).
2826
Georg Brandl50c40002012-06-24 11:45:20 +02002827 This function can support :ref:`specifying a file descriptor <path_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002828
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04002829 .. availability:: Unix.
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002830
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +00002831 .. versionchanged:: 3.2
2832 The :const:`ST_RDONLY` and :const:`ST_NOSUID` constants were added.
2833
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002834 .. versionadded:: 3.3
Cheryl Sabellae1521692019-05-06 08:39:13 -04002835 Added support for specifying *path* as an open file descriptor.
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002836
doko@ubuntu.comca616a22013-12-08 15:23:07 +01002837 .. versionchanged:: 3.4
2838 The :const:`ST_NODEV`, :const:`ST_NOEXEC`, :const:`ST_SYNCHRONOUS`,
2839 :const:`ST_MANDLOCK`, :const:`ST_WRITE`, :const:`ST_APPEND`,
2840 :const:`ST_IMMUTABLE`, :const:`ST_NOATIME`, :const:`ST_NODIRATIME`,
2841 and :const:`ST_RELATIME` constants were added.
2842
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002843 .. versionchanged:: 3.6
2844 Accepts a :term:`path-like object`.
Georg Brandl116aa622007-08-15 14:28:22 +00002845
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002846 .. versionadded:: 3.7
2847 Added :attr:`f_fsid`.
2848
Larry Hastings9cf065c2012-06-22 16:30:09 -07002849
2850.. data:: supports_dir_fd
2851
Cheryl Sabellae1521692019-05-06 08:39:13 -04002852 A :class:`set` object indicating which functions in the :mod:`os`
2853 module accept an open file descriptor for their *dir_fd* parameter.
2854 Different platforms provide different features, and the underlying
2855 functionality Python uses to implement the *dir_fd* parameter is not
2856 available on all platforms Python supports. For consistency's sake,
2857 functions that may support *dir_fd* always allow specifying the
2858 parameter, but will throw an exception if the functionality is used
2859 when it's not locally available. (Specifying ``None`` for *dir_fd*
2860 is always supported on all platforms.)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002861
Cheryl Sabellae1521692019-05-06 08:39:13 -04002862 To check whether a particular function accepts an open file descriptor
2863 for its *dir_fd* parameter, use the ``in`` operator on ``supports_dir_fd``.
2864 As an example, this expression evaluates to ``True`` if :func:`os.stat`
2865 accepts open file descriptors for *dir_fd* on the local platform::
Larry Hastings9cf065c2012-06-22 16:30:09 -07002866
2867 os.stat in os.supports_dir_fd
2868
Cheryl Sabellae1521692019-05-06 08:39:13 -04002869 Currently *dir_fd* parameters only work on Unix platforms;
2870 none of them work on Windows.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002871
2872 .. versionadded:: 3.3
2873
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002874
Larry Hastings9cf065c2012-06-22 16:30:09 -07002875.. data:: supports_effective_ids
2876
Cheryl Sabellae1521692019-05-06 08:39:13 -04002877 A :class:`set` object indicating whether :func:`os.access` permits
2878 specifying ``True`` for its *effective_ids* parameter on the local platform.
2879 (Specifying ``False`` for *effective_ids* is always supported on all
2880 platforms.) If the local platform supports it, the collection will contain
2881 :func:`os.access`; otherwise it will be empty.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002882
Cheryl Sabellae1521692019-05-06 08:39:13 -04002883 This expression evaluates to ``True`` if :func:`os.access` supports
2884 ``effective_ids=True`` on the local platform::
Larry Hastings9cf065c2012-06-22 16:30:09 -07002885
2886 os.access in os.supports_effective_ids
2887
Cheryl Sabellae1521692019-05-06 08:39:13 -04002888 Currently *effective_ids* is only supported on Unix platforms;
2889 it does not work on Windows.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002890
2891 .. versionadded:: 3.3
2892
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002893
Larry Hastings9cf065c2012-06-22 16:30:09 -07002894.. data:: supports_fd
2895
Cheryl Sabellae1521692019-05-06 08:39:13 -04002896 A :class:`set` object indicating which functions in the
Georg Brandlaceaf902012-06-25 08:33:56 +02002897 :mod:`os` module permit specifying their *path* parameter as an open file
Cheryl Sabellae1521692019-05-06 08:39:13 -04002898 descriptor on the local platform. Different platforms provide different
2899 features, and the underlying functionality Python uses to accept open file
2900 descriptors as *path* arguments is not available on all platforms Python
2901 supports.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002902
Cheryl Sabellae1521692019-05-06 08:39:13 -04002903 To determine whether a particular function permits specifying an open file
Larry Hastings9cf065c2012-06-22 16:30:09 -07002904 descriptor for its *path* parameter, use the ``in`` operator on
Cheryl Sabellae1521692019-05-06 08:39:13 -04002905 ``supports_fd``. As an example, this expression evaluates to ``True`` if
2906 :func:`os.chdir` accepts open file descriptors for *path* on your local
Larry Hastings9cf065c2012-06-22 16:30:09 -07002907 platform::
2908
2909 os.chdir in os.supports_fd
2910
2911 .. versionadded:: 3.3
2912
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002913
Larry Hastings9cf065c2012-06-22 16:30:09 -07002914.. data:: supports_follow_symlinks
2915
Cheryl Sabellae1521692019-05-06 08:39:13 -04002916 A :class:`set` object indicating which functions in the :mod:`os` module
2917 accept ``False`` for their *follow_symlinks* parameter on the local platform.
2918 Different platforms provide different features, and the underlying
2919 functionality Python uses to implement *follow_symlinks* is not available
2920 on all platforms Python supports. For consistency's sake, functions that
2921 may support *follow_symlinks* always allow specifying the parameter, but
2922 will throw an exception if the functionality is used when it's not locally
2923 available. (Specifying ``True`` for *follow_symlinks* is always supported
2924 on all platforms.)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002925
Cheryl Sabellae1521692019-05-06 08:39:13 -04002926 To check whether a particular function accepts ``False`` for its
2927 *follow_symlinks* parameter, use the ``in`` operator on
2928 ``supports_follow_symlinks``. As an example, this expression evaluates
2929 to ``True`` if you may specify ``follow_symlinks=False`` when calling
2930 :func:`os.stat` on the local platform::
Larry Hastings9cf065c2012-06-22 16:30:09 -07002931
2932 os.stat in os.supports_follow_symlinks
2933
2934 .. versionadded:: 3.3
2935
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002936
Martin Panterbf19d162015-09-09 01:01:13 +00002937.. function:: symlink(src, dst, target_is_directory=False, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002938
Martin Panterbf19d162015-09-09 01:01:13 +00002939 Create a symbolic link pointing to *src* named *dst*.
Brian Curtinc7395692010-07-09 15:15:09 +00002940
Larry Hastings9cf065c2012-06-22 16:30:09 -07002941 On Windows, a symlink represents either a file or a directory, and does not
Jason R. Coombs3a092862013-05-27 23:21:28 -04002942 morph to the target dynamically. If the target is present, the type of the
2943 symlink will be created to match. Otherwise, the symlink will be created
2944 as a directory if *target_is_directory* is ``True`` or a file symlink (the
l-n-sdaeb3c42018-11-14 00:13:12 +00002945 default) otherwise. On non-Windows platforms, *target_is_directory* is ignored.
Brian Curtind40e6f72010-07-08 21:39:08 +00002946
Georg Brandl50c40002012-06-24 11:45:20 +02002947 This function can support :ref:`paths relative to directory descriptors
2948 <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002949
Brian Curtin52173d42010-12-02 18:29:18 +00002950 .. note::
2951
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02002952 On newer versions of Windows 10, unprivileged accounts can create symlinks
2953 if Developer Mode is enabled. When Developer Mode is not available/enabled,
2954 the *SeCreateSymbolicLinkPrivilege* privilege is required, or the process
2955 must be run as an administrator.
Brian Curtin96245592010-12-28 17:08:22 +00002956
Jason R. Coombs3a092862013-05-27 23:21:28 -04002957
Brian Curtin96245592010-12-28 17:08:22 +00002958 :exc:`OSError` is raised when the function is called by an unprivileged
2959 user.
Brian Curtind40e6f72010-07-08 21:39:08 +00002960
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002961 .. audit-event:: os.symlink src,dst,dir_fd os.symlink
2962
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04002963 .. availability:: Unix, Windows.
Brian Curtinc7395692010-07-09 15:15:09 +00002964
Georg Brandlb3823372010-07-10 08:58:37 +00002965 .. versionchanged:: 3.2
2966 Added support for Windows 6.0 (Vista) symbolic links.
Georg Brandl116aa622007-08-15 14:28:22 +00002967
Larry Hastings9cf065c2012-06-22 16:30:09 -07002968 .. versionadded:: 3.3
2969 Added the *dir_fd* argument, and now allow *target_is_directory*
2970 on non-Windows platforms.
2971
Brett Cannon6fa7aad2016-09-06 15:55:02 -07002972 .. versionchanged:: 3.6
2973 Accepts a :term:`path-like object` for *src* and *dst*.
2974
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02002975 .. versionchanged:: 3.8
2976 Added support for unelevated symlinks on Windows with Developer Mode.
2977
Georg Brandl116aa622007-08-15 14:28:22 +00002978
Ross Lagerwall7807c352011-03-17 20:20:30 +02002979.. function:: sync()
2980
2981 Force write of everything to disk.
2982
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04002983 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02002984
2985 .. versionadded:: 3.3
2986
2987
2988.. function:: truncate(path, length)
2989
2990 Truncate the file corresponding to *path*, so that it is at most
2991 *length* bytes in size.
2992
Georg Brandl306336b2012-06-24 12:55:33 +02002993 This function can support :ref:`specifying a file descriptor <path_fd>`.
2994
Steve Dower44f91c32019-06-27 10:47:59 -07002995 .. audit-event:: os.truncate path,length os.truncate
Steve Dowerb82e17e2019-05-23 08:45:22 -07002996
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04002997 .. availability:: Unix, Windows.
Ross Lagerwall7807c352011-03-17 20:20:30 +02002998
2999 .. versionadded:: 3.3
3000
Steve Dowerfe0a41a2015-03-20 19:50:46 -07003001 .. versionchanged:: 3.5
3002 Added support for Windows
Ross Lagerwall7807c352011-03-17 20:20:30 +02003003
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003004 .. versionchanged:: 3.6
3005 Accepts a :term:`path-like object`.
3006
3007
Larry Hastingsb698d8e2012-06-23 16:55:07 -07003008.. function:: unlink(path, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003009
Brett Cannon05039172015-12-28 17:28:19 -08003010 Remove (delete) the file *path*. This function is semantically
3011 identical to :func:`remove`; the ``unlink`` name is its
3012 traditional Unix name. Please see the documentation for
3013 :func:`remove` for further information.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003014
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003015 .. audit-event:: os.remove path,dir_fd os.unlink
3016
Larry Hastings9cf065c2012-06-22 16:30:09 -07003017 .. versionadded:: 3.3
Larry Hastingsb698d8e2012-06-23 16:55:07 -07003018 The *dir_fd* parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00003019
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003020 .. versionchanged:: 3.6
3021 Accepts a :term:`path-like object`.
3022
Larry Hastings9cf065c2012-06-22 16:30:09 -07003023
Martin Panterbf19d162015-09-09 01:01:13 +00003024.. function:: utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00003025
Larry Hastings76ad59b2012-05-03 00:30:07 -07003026 Set the access and modified times of the file specified by *path*.
3027
3028 :func:`utime` takes two optional parameters, *times* and *ns*.
3029 These specify the times set on *path* and are used as follows:
3030
Martin Panterbf19d162015-09-09 01:01:13 +00003031 - If *ns* is specified,
Larry Hastings76ad59b2012-05-03 00:30:07 -07003032 it must be a 2-tuple of the form ``(atime_ns, mtime_ns)``
3033 where each member is an int expressing nanoseconds.
Larry Hastings9cf065c2012-06-22 16:30:09 -07003034 - If *times* is not ``None``,
Larry Hastings76ad59b2012-05-03 00:30:07 -07003035 it must be a 2-tuple of the form ``(atime, mtime)``
3036 where each member is an int or float expressing seconds.
Martin Panterbf19d162015-09-09 01:01:13 +00003037 - If *times* is ``None`` and *ns* is unspecified,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003038 this is equivalent to specifying ``ns=(atime_ns, mtime_ns)``
Larry Hastings76ad59b2012-05-03 00:30:07 -07003039 where both times are the current time.
Larry Hastings76ad59b2012-05-03 00:30:07 -07003040
Larry Hastings9cf065c2012-06-22 16:30:09 -07003041 It is an error to specify tuples for both *times* and *ns*.
Larry Hastings76ad59b2012-05-03 00:30:07 -07003042
Stéphane Wirtel7508a542018-05-01 12:02:26 +02003043 Note that the exact times you set here may not be returned by a subsequent
3044 :func:`~os.stat` call, depending on the resolution with which your operating
3045 system records access and modification times; see :func:`~os.stat`. The best
3046 way to preserve exact times is to use the *st_atime_ns* and *st_mtime_ns*
3047 fields from the :func:`os.stat` result object with the *ns* parameter to
3048 `utime`.
Georg Brandl116aa622007-08-15 14:28:22 +00003049
Georg Brandl50c40002012-06-24 11:45:20 +02003050 This function can support :ref:`specifying a file descriptor <path_fd>`,
3051 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
3052 following symlinks <follow_symlinks>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07003053
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003054 .. audit-event:: os.utime path,times,ns,dir_fd os.utime
3055
Larry Hastings76ad59b2012-05-03 00:30:07 -07003056 .. versionadded:: 3.3
Cheryl Sabellae1521692019-05-06 08:39:13 -04003057 Added support for specifying *path* as an open file descriptor,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003058 and the *dir_fd*, *follow_symlinks*, and *ns* parameters.
Larry Hastings76ad59b2012-05-03 00:30:07 -07003059
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003060 .. versionchanged:: 3.6
3061 Accepts a :term:`path-like object`.
3062
Georg Brandl116aa622007-08-15 14:28:22 +00003063
Georg Brandl18244152009-09-02 20:34:52 +00003064.. function:: walk(top, topdown=True, onerror=None, followlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +00003065
3066 .. index::
3067 single: directory; walking
3068 single: directory; traversal
3069
Christian Heimesfaf2f632008-01-06 16:59:19 +00003070 Generate the file names in a directory tree by walking the tree
3071 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl116aa622007-08-15 14:28:22 +00003072 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
3073 filenames)``.
3074
3075 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
3076 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
3077 *filenames* is a list of the names of the non-directory files in *dirpath*.
3078 Note that the names in the lists contain no path components. To get a full path
3079 (which begins with *top*) to a file or directory in *dirpath*, do
Serhiy Storchaka306cfb32020-09-04 21:19:30 +03003080 ``os.path.join(dirpath, name)``. Whether or not the lists are sorted
3081 depends on the file system. If a file is removed from or added to the
3082 *dirpath* directory during generating the lists, whether a name for that
3083 file be included is unspecified.
Georg Brandl116aa622007-08-15 14:28:22 +00003084
Christian Heimesfaf2f632008-01-06 16:59:19 +00003085 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00003086 directory is generated before the triples for any of its subdirectories
Benjamin Petersone58e0c72014-06-15 20:51:12 -07003087 (directories are generated top-down). If *topdown* is ``False``, the triple
3088 for a directory is generated after the triples for all of its subdirectories
3089 (directories are generated bottom-up). No matter the value of *topdown*, the
3090 list of subdirectories is retrieved before the tuples for the directory and
3091 its subdirectories are generated.
Georg Brandl116aa622007-08-15 14:28:22 +00003092
Christian Heimesfaf2f632008-01-06 16:59:19 +00003093 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl116aa622007-08-15 14:28:22 +00003094 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
3095 recurse into the subdirectories whose names remain in *dirnames*; this can be
3096 used to prune the search, impose a specific order of visiting, or even to inform
3097 :func:`walk` about directories the caller creates or renames before it resumes
Victor Stinner0e316f62015-10-23 12:38:11 +02003098 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` has
3099 no effect on the behavior of the walk, because in bottom-up mode the directories
3100 in *dirnames* are generated before *dirpath* itself is generated.
Georg Brandl116aa622007-08-15 14:28:22 +00003101
Andrés Delfinobadb8942018-04-02 23:48:54 -03003102 By default, errors from the :func:`scandir` call are ignored. If optional
Georg Brandl116aa622007-08-15 14:28:22 +00003103 argument *onerror* is specified, it should be a function; it will be called with
3104 one argument, an :exc:`OSError` instance. It can report the error to continue
3105 with the walk, or raise the exception to abort the walk. Note that the filename
3106 is available as the ``filename`` attribute of the exception object.
3107
3108 By default, :func:`walk` will not walk down into symbolic links that resolve to
Christian Heimesfaf2f632008-01-06 16:59:19 +00003109 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl116aa622007-08-15 14:28:22 +00003110 symlinks, on systems that support them.
3111
Georg Brandl116aa622007-08-15 14:28:22 +00003112 .. note::
3113
Georg Brandl50c40002012-06-24 11:45:20 +02003114 Be aware that setting *followlinks* to ``True`` can lead to infinite
3115 recursion if a link points to a parent directory of itself. :func:`walk`
3116 does not keep track of the directories it visited already.
Georg Brandl116aa622007-08-15 14:28:22 +00003117
3118 .. note::
3119
3120 If you pass a relative pathname, don't change the current working directory
3121 between resumptions of :func:`walk`. :func:`walk` never changes the current
3122 directory, and assumes that its caller doesn't either.
3123
3124 This example displays the number of bytes taken by non-directory files in each
3125 directory under the starting directory, except that it doesn't look under any
3126 CVS subdirectory::
3127
3128 import os
3129 from os.path import join, getsize
3130 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00003131 print(root, "consumes", end=" ")
3132 print(sum(getsize(join(root, name)) for name in files), end=" ")
3133 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00003134 if 'CVS' in dirs:
3135 dirs.remove('CVS') # don't visit CVS directories
3136
Victor Stinner47c41b42015-03-10 13:31:47 +01003137 In the next example (simple implementation of :func:`shutil.rmtree`),
3138 walking the tree bottom-up is essential, :func:`rmdir` doesn't allow
3139 deleting a directory before the directory is empty::
Georg Brandl116aa622007-08-15 14:28:22 +00003140
Christian Heimesfaf2f632008-01-06 16:59:19 +00003141 # Delete everything reachable from the directory named in "top",
Georg Brandl116aa622007-08-15 14:28:22 +00003142 # assuming there are no symbolic links.
3143 # CAUTION: This is dangerous! For example, if top == '/', it
3144 # could delete all your disk files.
3145 import os
3146 for root, dirs, files in os.walk(top, topdown=False):
3147 for name in files:
3148 os.remove(os.path.join(root, name))
3149 for name in dirs:
3150 os.rmdir(os.path.join(root, name))
3151
Serhiy Storchakadb283b32020-03-08 14:31:47 +02003152 .. audit-event:: os.walk top,topdown,onerror,followlinks os.walk
3153
Victor Stinner524a5ba2015-03-10 13:20:34 +01003154 .. versionchanged:: 3.5
Victor Stinner51b58322015-05-15 09:12:58 +02003155 This function now calls :func:`os.scandir` instead of :func:`os.listdir`,
3156 making it faster by reducing the number of calls to :func:`os.stat`.
Victor Stinner524a5ba2015-03-10 13:20:34 +01003157
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003158 .. versionchanged:: 3.6
3159 Accepts a :term:`path-like object`.
3160
Georg Brandl116aa622007-08-15 14:28:22 +00003161
Larry Hastingsb4038062012-07-15 10:57:38 -07003162.. function:: fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)
Charles-François Natali7372b062012-02-05 15:15:38 +01003163
3164 .. index::
3165 single: directory; walking
3166 single: directory; traversal
3167
Eli Benderskyd049d5c2012-02-11 09:52:29 +02003168 This behaves exactly like :func:`walk`, except that it yields a 4-tuple
Larry Hastingsc48fe982012-06-25 04:49:05 -07003169 ``(dirpath, dirnames, filenames, dirfd)``, and it supports ``dir_fd``.
Charles-François Natali7372b062012-02-05 15:15:38 +01003170
3171 *dirpath*, *dirnames* and *filenames* are identical to :func:`walk` output,
3172 and *dirfd* is a file descriptor referring to the directory *dirpath*.
3173
Larry Hastingsc48fe982012-06-25 04:49:05 -07003174 This function always supports :ref:`paths relative to directory descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -07003175 <dir_fd>` and :ref:`not following symlinks <follow_symlinks>`. Note however
Larry Hastings950b76a2012-07-15 17:32:36 -07003176 that, unlike other functions, the :func:`fwalk` default value for
Larry Hastingsb4038062012-07-15 10:57:38 -07003177 *follow_symlinks* is ``False``.
Larry Hastingsc48fe982012-06-25 04:49:05 -07003178
Charles-François Natali7372b062012-02-05 15:15:38 +01003179 .. note::
3180
3181 Since :func:`fwalk` yields file descriptors, those are only valid until
3182 the next iteration step, so you should duplicate them (e.g. with
3183 :func:`dup`) if you want to keep them longer.
3184
3185 This example displays the number of bytes taken by non-directory files in each
3186 directory under the starting directory, except that it doesn't look under any
3187 CVS subdirectory::
3188
3189 import os
3190 for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
3191 print(root, "consumes", end="")
Hynek Schlawack1729b8f2012-06-24 16:11:08 +02003192 print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
Charles-François Natali7372b062012-02-05 15:15:38 +01003193 end="")
3194 print("bytes in", len(files), "non-directory files")
3195 if 'CVS' in dirs:
3196 dirs.remove('CVS') # don't visit CVS directories
3197
3198 In the next example, walking the tree bottom-up is essential:
Victor Stinner69a6ca52012-08-05 15:18:02 +02003199 :func:`rmdir` doesn't allow deleting a directory before the directory is
Charles-François Natali7372b062012-02-05 15:15:38 +01003200 empty::
3201
3202 # Delete everything reachable from the directory named in "top",
3203 # assuming there are no symbolic links.
3204 # CAUTION: This is dangerous! For example, if top == '/', it
3205 # could delete all your disk files.
3206 import os
3207 for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
3208 for name in files:
Victor Stinner69a6ca52012-08-05 15:18:02 +02003209 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +01003210 for name in dirs:
Victor Stinner69a6ca52012-08-05 15:18:02 +02003211 os.rmdir(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +01003212
Serhiy Storchakadb283b32020-03-08 14:31:47 +02003213 .. audit-event:: os.fwalk top,topdown,onerror,follow_symlinks,dir_fd os.fwalk
3214
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003215 .. availability:: Unix.
Charles-François Natali7372b062012-02-05 15:15:38 +01003216
3217 .. versionadded:: 3.3
3218
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003219 .. versionchanged:: 3.6
3220 Accepts a :term:`path-like object`.
3221
Serhiy Storchaka8f6b3442017-03-07 14:33:21 +02003222 .. versionchanged:: 3.7
3223 Added support for :class:`bytes` paths.
3224
Charles-François Natali7372b062012-02-05 15:15:38 +01003225
Zackery Spytz43fdbd22019-05-29 13:57:07 -06003226.. function:: memfd_create(name[, flags=os.MFD_CLOEXEC])
3227
3228 Create an anonymous file and return a file descriptor that refers to it.
3229 *flags* must be one of the ``os.MFD_*`` constants available on the system
3230 (or a bitwise ORed combination of them). By default, the new file
3231 descriptor is :ref:`non-inheritable <fd_inheritance>`.
3232
Victor Stinnerccf0efb2019-06-05 12:24:52 +02003233 The name supplied in *name* is used as a filename and will be displayed as
3234 the target of the corresponding symbolic link in the directory
3235 ``/proc/self/fd/``. The displayed name is always prefixed with ``memfd:``
3236 and serves only for debugging purposes. Names do not affect the behavior of
3237 the file descriptor, and as such multiple files can have the same name
3238 without any side effects.
3239
Zackery Spytz43fdbd22019-05-29 13:57:07 -06003240 .. availability:: Linux 3.17 or newer with glibc 2.27 or newer.
3241
3242 .. versionadded:: 3.8
3243
3244
3245.. data:: MFD_CLOEXEC
3246 MFD_ALLOW_SEALING
3247 MFD_HUGETLB
3248 MFD_HUGE_SHIFT
3249 MFD_HUGE_MASK
3250 MFD_HUGE_64KB
3251 MFD_HUGE_512KB
3252 MFD_HUGE_1MB
3253 MFD_HUGE_2MB
3254 MFD_HUGE_8MB
3255 MFD_HUGE_16MB
3256 MFD_HUGE_32MB
3257 MFD_HUGE_256MB
3258 MFD_HUGE_512MB
3259 MFD_HUGE_1GB
3260 MFD_HUGE_2GB
3261 MFD_HUGE_16GB
3262
3263 These flags can be passed to :func:`memfd_create`.
3264
3265 .. availability:: Linux 3.17 or newer with glibc 2.27 or newer. The
3266 ``MFD_HUGE*`` flags are only available since Linux 4.14.
3267
3268 .. versionadded:: 3.8
3269
3270
Georg Brandlb9831ab2012-06-24 11:57:07 +02003271Linux extended attributes
3272~~~~~~~~~~~~~~~~~~~~~~~~~
3273
3274.. versionadded:: 3.3
3275
3276These functions are all available on Linux only.
3277
3278.. function:: getxattr(path, attribute, *, follow_symlinks=True)
3279
3280 Return the value of the extended filesystem attribute *attribute* for
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003281 *path*. *attribute* can be bytes or str (directly or indirectly through the
3282 :class:`PathLike` interface). If it is str, it is encoded with the filesystem
3283 encoding.
Georg Brandlb9831ab2012-06-24 11:57:07 +02003284
3285 This function can support :ref:`specifying a file descriptor <path_fd>` and
3286 :ref:`not following symlinks <follow_symlinks>`.
3287
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003288 .. audit-event:: os.getxattr path,attribute os.getxattr
3289
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003290 .. versionchanged:: 3.6
Berker Peksagd4d48742017-02-19 03:17:35 +03003291 Accepts a :term:`path-like object` for *path* and *attribute*.
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003292
Georg Brandlb9831ab2012-06-24 11:57:07 +02003293
3294.. function:: listxattr(path=None, *, follow_symlinks=True)
3295
3296 Return a list of the extended filesystem attributes on *path*. The
3297 attributes in the list are represented as strings decoded with the filesystem
3298 encoding. If *path* is ``None``, :func:`listxattr` will examine the current
3299 directory.
3300
3301 This function can support :ref:`specifying a file descriptor <path_fd>` and
3302 :ref:`not following symlinks <follow_symlinks>`.
3303
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003304 .. audit-event:: os.listxattr path os.listxattr
3305
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003306 .. versionchanged:: 3.6
3307 Accepts a :term:`path-like object`.
3308
Georg Brandlb9831ab2012-06-24 11:57:07 +02003309
3310.. function:: removexattr(path, attribute, *, follow_symlinks=True)
3311
3312 Removes the extended filesystem attribute *attribute* from *path*.
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003313 *attribute* should be bytes or str (directly or indirectly through the
3314 :class:`PathLike` interface). If it is a string, it is encoded
Victor Stinner4b9aad42020-11-02 16:49:54 +01003315 with the :term:`filesystem encoding and error handler`.
Georg Brandlb9831ab2012-06-24 11:57:07 +02003316
3317 This function can support :ref:`specifying a file descriptor <path_fd>` and
3318 :ref:`not following symlinks <follow_symlinks>`.
3319
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003320 .. audit-event:: os.removexattr path,attribute os.removexattr
3321
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003322 .. versionchanged:: 3.6
3323 Accepts a :term:`path-like object` for *path* and *attribute*.
3324
Georg Brandlb9831ab2012-06-24 11:57:07 +02003325
3326.. function:: setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)
3327
3328 Set the extended filesystem attribute *attribute* on *path* to *value*.
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003329 *attribute* must be a bytes or str with no embedded NULs (directly or
3330 indirectly through the :class:`PathLike` interface). If it is a str,
Victor Stinner4b9aad42020-11-02 16:49:54 +01003331 it is encoded with the :term:`filesystem encoding and error handler`. *flags* may be
Georg Brandlb9831ab2012-06-24 11:57:07 +02003332 :data:`XATTR_REPLACE` or :data:`XATTR_CREATE`. If :data:`XATTR_REPLACE` is
3333 given and the attribute does not exist, ``EEXISTS`` will be raised.
3334 If :data:`XATTR_CREATE` is given and the attribute already exists, the
3335 attribute will not be created and ``ENODATA`` will be raised.
3336
3337 This function can support :ref:`specifying a file descriptor <path_fd>` and
3338 :ref:`not following symlinks <follow_symlinks>`.
3339
3340 .. note::
3341
3342 A bug in Linux kernel versions less than 2.6.39 caused the flags argument
3343 to be ignored on some filesystems.
3344
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003345 .. audit-event:: os.setxattr path,attribute,value,flags os.setxattr
3346
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003347 .. versionchanged:: 3.6
3348 Accepts a :term:`path-like object` for *path* and *attribute*.
3349
Georg Brandlb9831ab2012-06-24 11:57:07 +02003350
3351.. data:: XATTR_SIZE_MAX
3352
3353 The maximum size the value of an extended attribute can be. Currently, this
Serhiy Storchakaf8def282013-02-16 17:29:56 +02003354 is 64 KiB on Linux.
Georg Brandlb9831ab2012-06-24 11:57:07 +02003355
3356
3357.. data:: XATTR_CREATE
3358
3359 This is a possible value for the flags argument in :func:`setxattr`. It
3360 indicates the operation must create an attribute.
3361
3362
3363.. data:: XATTR_REPLACE
3364
3365 This is a possible value for the flags argument in :func:`setxattr`. It
3366 indicates the operation must replace an existing attribute.
3367
3368
Georg Brandl116aa622007-08-15 14:28:22 +00003369.. _os-process:
3370
3371Process Management
3372------------------
3373
3374These functions may be used to create and manage processes.
3375
Serhiy Storchakadab83542013-10-13 20:12:43 +03003376The various :func:`exec\* <execl>` functions take a list of arguments for the new
Georg Brandl116aa622007-08-15 14:28:22 +00003377program loaded into the process. In each case, the first of these arguments is
3378passed to the new program as its own name rather than as an argument a user may
3379have typed on a command line. For the C programmer, this is the ``argv[0]``
Georg Brandl60203b42010-10-06 10:11:56 +00003380passed to a program's :c:func:`main`. For example, ``os.execv('/bin/echo',
Georg Brandl116aa622007-08-15 14:28:22 +00003381['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
3382to be ignored.
3383
3384
3385.. function:: abort()
3386
3387 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
3388 behavior is to produce a core dump; on Windows, the process immediately returns
Victor Stinner6e2e3b92011-07-08 02:26:39 +02003389 an exit code of ``3``. Be aware that calling this function will not call the
3390 Python signal handler registered for :const:`SIGABRT` with
3391 :func:`signal.signal`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003392
Georg Brandl116aa622007-08-15 14:28:22 +00003393
Steve Dower2438cdf2019-03-29 16:37:16 -07003394.. function:: add_dll_directory(path)
3395
3396 Add a path to the DLL search path.
3397
3398 This search path is used when resolving dependencies for imported
3399 extension modules (the module itself is resolved through sys.path),
3400 and also by :mod:`ctypes`.
3401
3402 Remove the directory by calling **close()** on the returned object
3403 or using it in a :keyword:`with` statement.
3404
3405 See the `Microsoft documentation
3406 <https://msdn.microsoft.com/44228cf2-6306-466c-8f16-f513cd3ba8b5>`_
3407 for more information about how DLLs are loaded.
3408
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003409 .. audit-event:: os.add_dll_directory path os.add_dll_directory
3410
Steve Dower2438cdf2019-03-29 16:37:16 -07003411 .. availability:: Windows.
3412
3413 .. versionadded:: 3.8
3414 Previous versions of CPython would resolve DLLs using the default
3415 behavior for the current process. This led to inconsistencies,
3416 such as only sometimes searching :envvar:`PATH` or the current
3417 working directory, and OS functions such as ``AddDllDirectory``
3418 having no effect.
3419
3420 In 3.8, the two primary ways DLLs are loaded now explicitly
3421 override the process-wide behavior to ensure consistency. See the
3422 :ref:`porting notes <bpo-36085-whatsnew>` for information on
3423 updating libraries.
3424
3425
Georg Brandl116aa622007-08-15 14:28:22 +00003426.. function:: execl(path, arg0, arg1, ...)
3427 execle(path, arg0, arg1, ..., env)
3428 execlp(file, arg0, arg1, ...)
3429 execlpe(file, arg0, arg1, ..., env)
3430 execv(path, args)
3431 execve(path, args, env)
3432 execvp(file, args)
3433 execvpe(file, args, env)
3434
3435 These functions all execute a new program, replacing the current process; they
3436 do not return. On Unix, the new executable is loaded into the current process,
Christian Heimesfaf2f632008-01-06 16:59:19 +00003437 and will have the same process id as the caller. Errors will be reported as
Georg Brandl48310cd2009-01-03 21:18:54 +00003438 :exc:`OSError` exceptions.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00003439
3440 The current process is replaced immediately. Open file objects and
3441 descriptors are not flushed, so if there may be data buffered
3442 on these open files, you should flush them using
3443 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
Serhiy Storchakadab83542013-10-13 20:12:43 +03003444 :func:`exec\* <execl>` function.
Georg Brandl116aa622007-08-15 14:28:22 +00003445
Serhiy Storchakadab83542013-10-13 20:12:43 +03003446 The "l" and "v" variants of the :func:`exec\* <execl>` functions differ in how
Christian Heimesfaf2f632008-01-06 16:59:19 +00003447 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00003448 to work with if the number of parameters is fixed when the code is written; the
3449 individual parameters simply become additional parameters to the :func:`execl\*`
Christian Heimesfaf2f632008-01-06 16:59:19 +00003450 functions. The "v" variants are good when the number of parameters is
Georg Brandl116aa622007-08-15 14:28:22 +00003451 variable, with the arguments being passed in a list or tuple as the *args*
3452 parameter. In either case, the arguments to the child process should start with
3453 the name of the command being run, but this is not enforced.
3454
Christian Heimesfaf2f632008-01-06 16:59:19 +00003455 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00003456 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
3457 :envvar:`PATH` environment variable to locate the program *file*. When the
Serhiy Storchakadab83542013-10-13 20:12:43 +03003458 environment is being replaced (using one of the :func:`exec\*e <execl>` variants,
Georg Brandl116aa622007-08-15 14:28:22 +00003459 discussed in the next paragraph), the new environment is used as the source of
3460 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
3461 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
3462 locate the executable; *path* must contain an appropriate absolute or relative
3463 path.
3464
3465 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Christian Heimesfaf2f632008-01-06 16:59:19 +00003466 that these all end in "e"), the *env* parameter must be a mapping which is
Christian Heimesa342c012008-04-20 21:01:16 +00003467 used to define the environment variables for the new process (these are used
3468 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl116aa622007-08-15 14:28:22 +00003469 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
Georg Brandl48310cd2009-01-03 21:18:54 +00003470 inherit the environment of the current process.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00003471
Larry Hastings9cf065c2012-06-22 16:30:09 -07003472 For :func:`execve` on some platforms, *path* may also be specified as an open
3473 file descriptor. This functionality may not be supported on your platform;
3474 you can check whether or not it is available using :data:`os.supports_fd`.
3475 If it is unavailable, using it will raise a :exc:`NotImplementedError`.
3476
Saiyang Gou95f60012020-02-04 16:15:00 -08003477 .. audit-event:: os.exec path,args,env os.execl
3478
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003479 .. availability:: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00003480
Larry Hastings9cf065c2012-06-22 16:30:09 -07003481 .. versionadded:: 3.3
Cheryl Sabellae1521692019-05-06 08:39:13 -04003482 Added support for specifying *path* as an open file descriptor
Larry Hastings9cf065c2012-06-22 16:30:09 -07003483 for :func:`execve`.
Georg Brandl116aa622007-08-15 14:28:22 +00003484
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003485 .. versionchanged:: 3.6
3486 Accepts a :term:`path-like object`.
3487
Georg Brandl116aa622007-08-15 14:28:22 +00003488.. function:: _exit(n)
3489
Georg Brandl6f4e68d2010-10-17 10:51:45 +00003490 Exit the process with status *n*, without calling cleanup handlers, flushing
Benjamin Petersonf650e462010-05-06 23:03:05 +00003491 stdio buffers, etc.
3492
Georg Brandl116aa622007-08-15 14:28:22 +00003493 .. note::
3494
Georg Brandl6f4e68d2010-10-17 10:51:45 +00003495 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should
3496 normally only be used in the child process after a :func:`fork`.
Georg Brandl116aa622007-08-15 14:28:22 +00003497
Christian Heimesfaf2f632008-01-06 16:59:19 +00003498The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl116aa622007-08-15 14:28:22 +00003499although they are not required. These are typically used for system programs
3500written in Python, such as a mail server's external command delivery program.
3501
3502.. note::
3503
3504 Some of these may not be available on all Unix platforms, since there is some
3505 variation. These constants are defined where they are defined by the underlying
3506 platform.
3507
3508
3509.. data:: EX_OK
3510
Benjamin Petersonf650e462010-05-06 23:03:05 +00003511 Exit code that means no error occurred.
3512
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003513 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003514
Georg Brandl116aa622007-08-15 14:28:22 +00003515
3516.. data:: EX_USAGE
3517
3518 Exit code that means the command was used incorrectly, such as when the wrong
Benjamin Petersonf650e462010-05-06 23:03:05 +00003519 number of arguments are given.
3520
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003521 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003522
Georg Brandl116aa622007-08-15 14:28:22 +00003523
3524.. data:: EX_DATAERR
3525
Benjamin Petersonf650e462010-05-06 23:03:05 +00003526 Exit code that means the input data was incorrect.
3527
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003528 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003529
Georg Brandl116aa622007-08-15 14:28:22 +00003530
3531.. data:: EX_NOINPUT
3532
3533 Exit code that means an input file did not exist or was not readable.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003534
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003535 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003536
Georg Brandl116aa622007-08-15 14:28:22 +00003537
3538.. data:: EX_NOUSER
3539
Benjamin Petersonf650e462010-05-06 23:03:05 +00003540 Exit code that means a specified user did not exist.
3541
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003542 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003543
Georg Brandl116aa622007-08-15 14:28:22 +00003544
3545.. data:: EX_NOHOST
3546
Benjamin Petersonf650e462010-05-06 23:03:05 +00003547 Exit code that means a specified host did not exist.
3548
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003549 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003550
Georg Brandl116aa622007-08-15 14:28:22 +00003551
3552.. data:: EX_UNAVAILABLE
3553
Benjamin Petersonf650e462010-05-06 23:03:05 +00003554 Exit code that means that a required service is unavailable.
3555
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003556 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003557
Georg Brandl116aa622007-08-15 14:28:22 +00003558
3559.. data:: EX_SOFTWARE
3560
Benjamin Petersonf650e462010-05-06 23:03:05 +00003561 Exit code that means an internal software error was detected.
3562
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003563 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003564
Georg Brandl116aa622007-08-15 14:28:22 +00003565
3566.. data:: EX_OSERR
3567
3568 Exit code that means an operating system error was detected, such as the
Benjamin Petersonf650e462010-05-06 23:03:05 +00003569 inability to fork or create a pipe.
3570
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003571 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003572
Georg Brandl116aa622007-08-15 14:28:22 +00003573
3574.. data:: EX_OSFILE
3575
3576 Exit code that means some system file did not exist, could not be opened, or had
Benjamin Petersonf650e462010-05-06 23:03:05 +00003577 some other kind of error.
3578
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003579 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003580
Georg Brandl116aa622007-08-15 14:28:22 +00003581
3582.. data:: EX_CANTCREAT
3583
3584 Exit code that means a user specified output file could not be created.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003585
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003586 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003587
Georg Brandl116aa622007-08-15 14:28:22 +00003588
3589.. data:: EX_IOERR
3590
3591 Exit code that means that an error occurred while doing I/O on some file.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003592
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003593 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003594
Georg Brandl116aa622007-08-15 14:28:22 +00003595
3596.. data:: EX_TEMPFAIL
3597
3598 Exit code that means a temporary failure occurred. This indicates something
3599 that may not really be an error, such as a network connection that couldn't be
Benjamin Petersonf650e462010-05-06 23:03:05 +00003600 made during a retryable operation.
3601
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003602 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003603
Georg Brandl116aa622007-08-15 14:28:22 +00003604
3605.. data:: EX_PROTOCOL
3606
3607 Exit code that means that a protocol exchange was illegal, invalid, or not
Benjamin Petersonf650e462010-05-06 23:03:05 +00003608 understood.
3609
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003610 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003611
Georg Brandl116aa622007-08-15 14:28:22 +00003612
3613.. data:: EX_NOPERM
3614
3615 Exit code that means that there were insufficient permissions to perform the
Benjamin Petersonf650e462010-05-06 23:03:05 +00003616 operation (but not intended for file system problems).
3617
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003618 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003619
Georg Brandl116aa622007-08-15 14:28:22 +00003620
3621.. data:: EX_CONFIG
3622
3623 Exit code that means that some kind of configuration error occurred.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003624
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003625 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003626
Georg Brandl116aa622007-08-15 14:28:22 +00003627
3628.. data:: EX_NOTFOUND
3629
Benjamin Petersonf650e462010-05-06 23:03:05 +00003630 Exit code that means something like "an entry was not found".
3631
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003632 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003633
Georg Brandl116aa622007-08-15 14:28:22 +00003634
3635.. function:: fork()
3636
Christian Heimesfaf2f632008-01-06 16:59:19 +00003637 Fork a child process. Return ``0`` in the child and the child's process id in the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003638 parent. If an error occurs :exc:`OSError` is raised.
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +00003639
Larry Hastings3732ed22014-03-15 21:13:56 -07003640 Note that some platforms including FreeBSD <= 6.3 and Cygwin have
Phil Connellb2203002019-11-15 16:56:03 +00003641 known issues when using ``fork()`` from a thread.
3642
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003643 .. audit-event:: os.fork "" os.fork
3644
Phil Connellb2203002019-11-15 16:56:03 +00003645 .. versionchanged:: 3.8
3646 Calling ``fork()`` in a subinterpreter is no longer supported
3647 (:exc:`RuntimeError` is raised).
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +00003648
Christian Heimes3046fe42013-10-29 21:08:56 +01003649 .. warning::
3650
3651 See :mod:`ssl` for applications that use the SSL module with fork().
3652
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003653 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003654
3655
3656.. function:: forkpty()
3657
3658 Fork a child process, using a new pseudo-terminal as the child's controlling
3659 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
3660 new child's process id in the parent, and *fd* is the file descriptor of the
3661 master end of the pseudo-terminal. For a more portable approach, use the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003662 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003663
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003664 .. audit-event:: os.forkpty "" os.forkpty
3665
Phil Connellb2203002019-11-15 16:56:03 +00003666 .. versionchanged:: 3.8
3667 Calling ``forkpty()`` in a subinterpreter is no longer supported
3668 (:exc:`RuntimeError` is raised).
3669
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003670 .. availability:: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003671
3672
3673.. function:: kill(pid, sig)
3674
3675 .. index::
3676 single: process; killing
3677 single: process; signalling
3678
3679 Send signal *sig* to the process *pid*. Constants for the specific signals
3680 available on the host platform are defined in the :mod:`signal` module.
Brian Curtineb24d742010-04-12 17:16:38 +00003681
3682 Windows: The :data:`signal.CTRL_C_EVENT` and
3683 :data:`signal.CTRL_BREAK_EVENT` signals are special signals which can
3684 only be sent to console processes which share a common console window,
3685 e.g., some subprocesses. Any other value for *sig* will cause the process
3686 to be unconditionally killed by the TerminateProcess API, and the exit code
3687 will be set to *sig*. The Windows version of :func:`kill` additionally takes
3688 process handles to be killed.
Georg Brandl116aa622007-08-15 14:28:22 +00003689
Victor Stinnerb3e72192011-05-08 01:46:11 +02003690 See also :func:`signal.pthread_kill`.
3691
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003692 .. audit-event:: os.kill pid,sig os.kill
3693
Georg Brandl67b21b72010-08-17 15:07:14 +00003694 .. versionadded:: 3.2
3695 Windows support.
Brian Curtin904bd392010-04-20 15:28:06 +00003696
Georg Brandl116aa622007-08-15 14:28:22 +00003697
3698.. function:: killpg(pgid, sig)
3699
3700 .. index::
3701 single: process; killing
3702 single: process; signalling
3703
Benjamin Petersonf650e462010-05-06 23:03:05 +00003704 Send the signal *sig* to the process group *pgid*.
3705
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003706 .. audit-event:: os.killpg pgid,sig os.killpg
3707
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003708 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003709
Georg Brandl116aa622007-08-15 14:28:22 +00003710
3711.. function:: nice(increment)
3712
3713 Add *increment* to the process's "niceness". Return the new niceness.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003714
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003715 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003716
3717
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08003718.. function:: pidfd_open(pid, flags=0)
3719
3720 Return a file descriptor referring to the process *pid*. This descriptor can
3721 be used to perform process management without races and signals. The *flags*
3722 argument is provided for future extensions; no flag values are currently
3723 defined.
3724
3725 See the :manpage:`pidfd_open(2)` man page for more details.
3726
3727 .. availability:: Linux 5.3+
3728 .. versionadded:: 3.9
3729
3730
Georg Brandl116aa622007-08-15 14:28:22 +00003731.. function:: plock(op)
3732
3733 Lock program segments into memory. The value of *op* (defined in
Benjamin Petersonf650e462010-05-06 23:03:05 +00003734 ``<sys/lock.h>``) determines which segments are locked.
3735
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003736 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003737
3738
Martin Panterbf19d162015-09-09 01:01:13 +00003739.. function:: popen(cmd, mode='r', buffering=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00003740
Martin Panterbf19d162015-09-09 01:01:13 +00003741 Open a pipe to or from command *cmd*.
3742 The return value is an open file object
Andrew Kuchlingf5a42922014-04-16 09:10:53 -04003743 connected to the pipe, which can be read or written depending on whether *mode*
3744 is ``'r'`` (default) or ``'w'``. The *buffering* argument has the same meaning as
3745 the corresponding argument to the built-in :func:`open` function. The
3746 returned file object reads or writes text strings rather than bytes.
3747
3748 The ``close`` method returns :const:`None` if the subprocess exited
3749 successfully, or the subprocess's return code if there was an
3750 error. On POSIX systems, if the return code is positive it
3751 represents the return value of the process left-shifted by one
3752 byte. If the return code is negative, the process was terminated
3753 by the signal given by the negated value of the return code. (For
3754 example, the return value might be ``- signal.SIGKILL`` if the
3755 subprocess was killed.) On Windows systems, the return value
3756 contains the signed integer return code from the child process.
3757
Victor Stinner65a796e2020-04-01 18:49:29 +02003758 On Unix, :func:`waitstatus_to_exitcode` can be used to convert the ``close``
3759 method result (exit status) into an exit code if it is not ``None``. On
3760 Windows, the ``close`` method result is directly the exit code
3761 (or ``None``).
3762
Andrew Kuchlingf5a42922014-04-16 09:10:53 -04003763 This is implemented using :class:`subprocess.Popen`; see that class's
3764 documentation for more powerful ways to manage and communicate with
3765 subprocesses.
Georg Brandl116aa622007-08-15 14:28:22 +00003766
3767
Serhiy Storchakad700f972018-09-08 14:48:18 +03003768.. function:: posix_spawn(path, argv, env, *, file_actions=None, \
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03003769 setpgroup=None, resetids=False, setsid=False, setsigmask=(), \
Pablo Galindo254a4662018-09-07 16:44:24 +01003770 setsigdef=(), scheduler=None)
Gregory P. Smith79760ed2018-04-01 12:01:48 -07003771
Serhiy Storchakaef347532018-05-01 16:45:04 +03003772 Wraps the :c:func:`posix_spawn` C library API for use from Python.
Gregory P. Smith79760ed2018-04-01 12:01:48 -07003773
Serhiy Storchakaef347532018-05-01 16:45:04 +03003774 Most users should use :func:`subprocess.run` instead of :func:`posix_spawn`.
Gregory P. Smith79760ed2018-04-01 12:01:48 -07003775
Serhiy Storchakad700f972018-09-08 14:48:18 +03003776 The positional-only arguments *path*, *args*, and *env* are similar to
3777 :func:`execve`.
Gregory P. Smith79760ed2018-04-01 12:01:48 -07003778
Tomer Cohen5b57fa62020-10-20 12:08:58 +03003779 The *path* parameter is the path to the executable file. The *path* should
3780 contain a directory. Use :func:`posix_spawnp` to pass an executable file
Joannah Nanjekye92b83222019-01-16 16:29:26 +03003781 without directory.
3782
Gregory P. Smith79760ed2018-04-01 12:01:48 -07003783 The *file_actions* argument may be a sequence of tuples describing actions
3784 to take on specific file descriptors in the child process between the C
Serhiy Storchakaef347532018-05-01 16:45:04 +03003785 library implementation's :c:func:`fork` and :c:func:`exec` steps.
3786 The first item in each tuple must be one of the three type indicator
3787 listed below describing the remaining tuple elements:
Gregory P. Smith79760ed2018-04-01 12:01:48 -07003788
Serhiy Storchakaef347532018-05-01 16:45:04 +03003789 .. data:: POSIX_SPAWN_OPEN
Gregory P. Smith79760ed2018-04-01 12:01:48 -07003790
Serhiy Storchakaef347532018-05-01 16:45:04 +03003791 (``os.POSIX_SPAWN_OPEN``, *fd*, *path*, *flags*, *mode*)
3792
3793 Performs ``os.dup2(os.open(path, flags, mode), fd)``.
3794
3795 .. data:: POSIX_SPAWN_CLOSE
3796
3797 (``os.POSIX_SPAWN_CLOSE``, *fd*)
3798
3799 Performs ``os.close(fd)``.
3800
3801 .. data:: POSIX_SPAWN_DUP2
3802
3803 (``os.POSIX_SPAWN_DUP2``, *fd*, *new_fd*)
3804
3805 Performs ``os.dup2(fd, new_fd)``.
3806
3807 These tuples correspond to the C library
3808 :c:func:`posix_spawn_file_actions_addopen`,
3809 :c:func:`posix_spawn_file_actions_addclose`, and
3810 :c:func:`posix_spawn_file_actions_adddup2` API calls used to prepare
3811 for the :c:func:`posix_spawn` call itself.
Gregory P. Smith79760ed2018-04-01 12:01:48 -07003812
Pablo Galindo254a4662018-09-07 16:44:24 +01003813 The *setpgroup* argument will set the process group of the child to the value
3814 specified. If the value specified is 0, the child's process group ID will be
3815 made the same as its process ID. If the value of *setpgroup* is not set, the
3816 child will inherit the parent's process group ID. This argument corresponds
3817 to the C library :c:data:`POSIX_SPAWN_SETPGROUP` flag.
3818
3819 If the *resetids* argument is ``True`` it will reset the effective UID and
3820 GID of the child to the real UID and GID of the parent process. If the
3821 argument is ``False``, then the child retains the effective UID and GID of
3822 the parent. In either case, if the set-user-ID and set-group-ID permission
3823 bits are enabled on the executable file, their effect will override the
3824 setting of the effective UID and GID. This argument corresponds to the C
3825 library :c:data:`POSIX_SPAWN_RESETIDS` flag.
3826
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03003827 If the *setsid* argument is ``True``, it will create a new session ID
3828 for `posix_spawn`. *setsid* requires :c:data:`POSIX_SPAWN_SETSID`
3829 or :c:data:`POSIX_SPAWN_SETSID_NP` flag. Otherwise, :exc:`NotImplementedError`
3830 is raised.
3831
Pablo Galindo254a4662018-09-07 16:44:24 +01003832 The *setsigmask* argument will set the signal mask to the signal set
3833 specified. If the parameter is not used, then the child inherits the
3834 parent's signal mask. This argument corresponds to the C library
3835 :c:data:`POSIX_SPAWN_SETSIGMASK` flag.
3836
3837 The *sigdef* argument will reset the disposition of all signals in the set
3838 specified. This argument corresponds to the C library
3839 :c:data:`POSIX_SPAWN_SETSIGDEF` flag.
3840
3841 The *scheduler* argument must be a tuple containing the (optional) scheduler
3842 policy and an instance of :class:`sched_param` with the scheduler parameters.
3843 A value of ``None`` in the place of the scheduler policy indicates that is
3844 not being provided. This argument is a combination of the C library
3845 :c:data:`POSIX_SPAWN_SETSCHEDPARAM` and :c:data:`POSIX_SPAWN_SETSCHEDULER`
3846 flags.
3847
Saiyang Gou95f60012020-02-04 16:15:00 -08003848 .. audit-event:: os.posix_spawn path,argv,env os.posix_spawn
3849
Mark Williams8b504002019-03-03 09:42:25 -08003850 .. versionadded:: 3.8
Gregory P. Smith79760ed2018-04-01 12:01:48 -07003851
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03003852 .. availability:: Unix.
Gregory P. Smith79760ed2018-04-01 12:01:48 -07003853
Joannah Nanjekye92b83222019-01-16 16:29:26 +03003854.. function:: posix_spawnp(path, argv, env, *, file_actions=None, \
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03003855 setpgroup=None, resetids=False, setsid=False, setsigmask=(), \
Joannah Nanjekye92b83222019-01-16 16:29:26 +03003856 setsigdef=(), scheduler=None)
3857
3858 Wraps the :c:func:`posix_spawnp` C library API for use from Python.
3859
3860 Similar to :func:`posix_spawn` except that the system searches
3861 for the *executable* file in the list of directories specified by the
3862 :envvar:`PATH` environment variable (in the same way as for ``execvp(3)``).
3863
Saiyang Gou95f60012020-02-04 16:15:00 -08003864 .. audit-event:: os.posix_spawn path,argv,env os.posix_spawnp
3865
Joannah Nanjekye92b83222019-01-16 16:29:26 +03003866 .. versionadded:: 3.8
3867
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03003868 .. availability:: See :func:`posix_spawn` documentation.
3869
Joannah Nanjekye92b83222019-01-16 16:29:26 +03003870
Gregory P. Smith163468a2017-05-29 10:03:41 -07003871.. function:: register_at_fork(*, before=None, after_in_parent=None, \
3872 after_in_child=None)
Antoine Pitrou346cbd32017-05-27 17:50:54 +02003873
Gregory P. Smith163468a2017-05-29 10:03:41 -07003874 Register callables to be executed when a new child process is forked
3875 using :func:`os.fork` or similar process cloning APIs.
3876 The parameters are optional and keyword-only.
3877 Each specifies a different call point.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02003878
Gregory P. Smith163468a2017-05-29 10:03:41 -07003879 * *before* is a function called before forking a child process.
3880 * *after_in_parent* is a function called from the parent process
3881 after forking a child process.
3882 * *after_in_child* is a function called from the child process.
3883
3884 These calls are only made if control is expected to return to the
3885 Python interpreter. A typical :mod:`subprocess` launch will not
3886 trigger them as the child is not going to re-enter the interpreter.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02003887
3888 Functions registered for execution before forking are called in
3889 reverse registration order. Functions registered for execution
3890 after forking (either in the parent or in the child) are called
3891 in registration order.
3892
3893 Note that :c:func:`fork` calls made by third-party C code may not
3894 call those functions, unless it explicitly calls :c:func:`PyOS_BeforeFork`,
3895 :c:func:`PyOS_AfterFork_Parent` and :c:func:`PyOS_AfterFork_Child`.
3896
Gregory P. Smith163468a2017-05-29 10:03:41 -07003897 There is no way to unregister a function.
3898
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003899 .. availability:: Unix.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02003900
3901 .. versionadded:: 3.7
3902
3903
Georg Brandl116aa622007-08-15 14:28:22 +00003904.. function:: spawnl(mode, path, ...)
3905 spawnle(mode, path, ..., env)
3906 spawnlp(mode, file, ...)
3907 spawnlpe(mode, file, ..., env)
3908 spawnv(mode, path, args)
3909 spawnve(mode, path, args, env)
3910 spawnvp(mode, file, args)
3911 spawnvpe(mode, file, args, env)
3912
3913 Execute the program *path* in a new process.
3914
3915 (Note that the :mod:`subprocess` module provides more powerful facilities for
3916 spawning new processes and retrieving their results; using that module is
Benjamin Peterson87c8d872009-06-11 22:54:11 +00003917 preferable to using these functions. Check especially the
3918 :ref:`subprocess-replacements` section.)
Georg Brandl116aa622007-08-15 14:28:22 +00003919
Christian Heimesfaf2f632008-01-06 16:59:19 +00003920 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl116aa622007-08-15 14:28:22 +00003921 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
3922 exits normally, or ``-signal``, where *signal* is the signal that killed the
Christian Heimesfaf2f632008-01-06 16:59:19 +00003923 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl116aa622007-08-15 14:28:22 +00003924 be used with the :func:`waitpid` function.
3925
pxinwrf2d7ac72019-05-21 18:46:37 +08003926 Note on VxWorks, this function doesn't return ``-signal`` when the new process is
3927 killed. Instead it raises OSError exception.
3928
Serhiy Storchakadab83542013-10-13 20:12:43 +03003929 The "l" and "v" variants of the :func:`spawn\* <spawnl>` functions differ in how
Christian Heimesfaf2f632008-01-06 16:59:19 +00003930 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00003931 to work with if the number of parameters is fixed when the code is written; the
3932 individual parameters simply become additional parameters to the
Christian Heimesfaf2f632008-01-06 16:59:19 +00003933 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl116aa622007-08-15 14:28:22 +00003934 parameters is variable, with the arguments being passed in a list or tuple as
3935 the *args* parameter. In either case, the arguments to the child process must
3936 start with the name of the command being run.
3937
Christian Heimesfaf2f632008-01-06 16:59:19 +00003938 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00003939 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
3940 :envvar:`PATH` environment variable to locate the program *file*. When the
Serhiy Storchakadab83542013-10-13 20:12:43 +03003941 environment is being replaced (using one of the :func:`spawn\*e <spawnl>` variants,
Georg Brandl116aa622007-08-15 14:28:22 +00003942 discussed in the next paragraph), the new environment is used as the source of
3943 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
3944 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
3945 :envvar:`PATH` variable to locate the executable; *path* must contain an
3946 appropriate absolute or relative path.
3947
3948 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Christian Heimesfaf2f632008-01-06 16:59:19 +00003949 (note that these all end in "e"), the *env* parameter must be a mapping
Christian Heimesa342c012008-04-20 21:01:16 +00003950 which is used to define the environment variables for the new process (they are
3951 used instead of the current process' environment); the functions
Georg Brandl116aa622007-08-15 14:28:22 +00003952 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
Benjamin Petersond23f8222009-04-05 19:13:16 +00003953 the new process to inherit the environment of the current process. Note that
3954 keys and values in the *env* dictionary must be strings; invalid keys or
3955 values will cause the function to fail, with a return value of ``127``.
Georg Brandl116aa622007-08-15 14:28:22 +00003956
3957 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
3958 equivalent::
3959
3960 import os
3961 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
3962
3963 L = ['cp', 'index.html', '/dev/null']
3964 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
3965
Saiyang Gou95f60012020-02-04 16:15:00 -08003966 .. audit-event:: os.spawn mode,path,args,env os.spawnl
3967
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003968 .. availability:: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
3969 and :func:`spawnvpe` are not available on Windows. :func:`spawnle` and
3970 :func:`spawnve` are not thread-safe on Windows; we advise you to use the
3971 :mod:`subprocess` module instead.
Georg Brandl116aa622007-08-15 14:28:22 +00003972
Brett Cannon6fa7aad2016-09-06 15:55:02 -07003973 .. versionchanged:: 3.6
3974 Accepts a :term:`path-like object`.
3975
Georg Brandl116aa622007-08-15 14:28:22 +00003976
3977.. data:: P_NOWAIT
3978 P_NOWAITO
3979
Serhiy Storchakadab83542013-10-13 20:12:43 +03003980 Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
Georg Brandl116aa622007-08-15 14:28:22 +00003981 functions. If either of these values is given, the :func:`spawn\*` functions
Christian Heimesfaf2f632008-01-06 16:59:19 +00003982 will return as soon as the new process has been created, with the process id as
Benjamin Petersonf650e462010-05-06 23:03:05 +00003983 the return value.
3984
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003985 .. availability:: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00003986
Georg Brandl116aa622007-08-15 14:28:22 +00003987
3988.. data:: P_WAIT
3989
Serhiy Storchakadab83542013-10-13 20:12:43 +03003990 Possible value for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
Georg Brandl116aa622007-08-15 14:28:22 +00003991 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
3992 return until the new process has run to completion and will return the exit code
3993 of the process the run is successful, or ``-signal`` if a signal kills the
Benjamin Petersonf650e462010-05-06 23:03:05 +00003994 process.
3995
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04003996 .. availability:: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00003997
Georg Brandl116aa622007-08-15 14:28:22 +00003998
3999.. data:: P_DETACH
4000 P_OVERLAY
4001
Serhiy Storchakadab83542013-10-13 20:12:43 +03004002 Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
Georg Brandl116aa622007-08-15 14:28:22 +00004003 functions. These are less portable than those listed above. :const:`P_DETACH`
4004 is similar to :const:`P_NOWAIT`, but the new process is detached from the
4005 console of the calling process. If :const:`P_OVERLAY` is used, the current
Serhiy Storchakadab83542013-10-13 20:12:43 +03004006 process will be replaced; the :func:`spawn\* <spawnl>` function will not return.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004007
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004008 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00004009
Georg Brandl116aa622007-08-15 14:28:22 +00004010
4011.. function:: startfile(path[, operation])
4012
4013 Start a file with its associated application.
4014
4015 When *operation* is not specified or ``'open'``, this acts like double-clicking
4016 the file in Windows Explorer, or giving the file name as an argument to the
4017 :program:`start` command from the interactive command shell: the file is opened
4018 with whatever application (if any) its extension is associated.
4019
4020 When another *operation* is given, it must be a "command verb" that specifies
4021 what should be done with the file. Common verbs documented by Microsoft are
4022 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
4023 ``'find'`` (to be used on directories).
4024
4025 :func:`startfile` returns as soon as the associated application is launched.
4026 There is no option to wait for the application to close, and no way to retrieve
4027 the application's exit status. The *path* parameter is relative to the current
4028 directory. If you want to use an absolute path, make sure the first character
Georg Brandl60203b42010-10-06 10:11:56 +00004029 is not a slash (``'/'``); the underlying Win32 :c:func:`ShellExecute` function
Georg Brandl116aa622007-08-15 14:28:22 +00004030 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
Benjamin Petersonf650e462010-05-06 23:03:05 +00004031 the path is properly encoded for Win32.
4032
Steve Dower7d0e0c92015-01-24 08:18:24 -08004033 To reduce interpreter startup overhead, the Win32 :c:func:`ShellExecute`
4034 function is not resolved until this function is first called. If the function
4035 cannot be resolved, :exc:`NotImplementedError` will be raised.
4036
Saiyang Gou95f60012020-02-04 16:15:00 -08004037 .. audit-event:: os.startfile path,operation os.startfile
4038
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004039 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00004040
Georg Brandl116aa622007-08-15 14:28:22 +00004041
4042.. function:: system(command)
4043
4044 Execute the command (a string) in a subshell. This is implemented by calling
Georg Brandl60203b42010-10-06 10:11:56 +00004045 the Standard C function :c:func:`system`, and has the same limitations.
Georg Brandl8f7b4272010-10-14 06:35:53 +00004046 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of
4047 the executed command. If *command* generates any output, it will be sent to
4048 the interpreter standard output stream.
Georg Brandl116aa622007-08-15 14:28:22 +00004049
4050 On Unix, the return value is the exit status of the process encoded in the
Georg Brandl8f7b4272010-10-14 06:35:53 +00004051 format specified for :func:`wait`. Note that POSIX does not specify the
4052 meaning of the return value of the C :c:func:`system` function, so the return
4053 value of the Python function is system-dependent.
Georg Brandl116aa622007-08-15 14:28:22 +00004054
Georg Brandl8f7b4272010-10-14 06:35:53 +00004055 On Windows, the return value is that returned by the system shell after
4056 running *command*. The shell is given by the Windows environment variable
4057 :envvar:`COMSPEC`: it is usually :program:`cmd.exe`, which returns the exit
4058 status of the command run; on systems using a non-native shell, consult your
4059 shell documentation.
Georg Brandl116aa622007-08-15 14:28:22 +00004060
Georg Brandl8f7b4272010-10-14 06:35:53 +00004061 The :mod:`subprocess` module provides more powerful facilities for spawning
4062 new processes and retrieving their results; using that module is preferable
4063 to using this function. See the :ref:`subprocess-replacements` section in
4064 the :mod:`subprocess` documentation for some helpful recipes.
Georg Brandl116aa622007-08-15 14:28:22 +00004065
Victor Stinner65a796e2020-04-01 18:49:29 +02004066 On Unix, :func:`waitstatus_to_exitcode` can be used to convert the result
4067 (exit status) into an exit code. On Windows, the result is directly the exit
4068 code.
4069
Steve Dower44f91c32019-06-27 10:47:59 -07004070 .. audit-event:: os.system command os.system
Steve Dowerb82e17e2019-05-23 08:45:22 -07004071
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004072 .. availability:: Unix, Windows.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004073
Georg Brandl116aa622007-08-15 14:28:22 +00004074
4075.. function:: times()
4076
Larry Hastings605a62d2012-06-24 04:33:36 -07004077 Returns the current global process times.
4078 The return value is an object with five attributes:
4079
4080 * :attr:`user` - user time
4081 * :attr:`system` - system time
4082 * :attr:`children_user` - user time of all child processes
4083 * :attr:`children_system` - system time of all child processes
4084 * :attr:`elapsed` - elapsed real time since a fixed point in the past
4085
4086 For backwards compatibility, this object also behaves like a five-tuple
4087 containing :attr:`user`, :attr:`system`, :attr:`children_user`,
4088 :attr:`children_system`, and :attr:`elapsed` in that order.
4089
4090 See the Unix manual page
Joannah Nanjekye3ccdbc32019-09-07 04:05:29 -03004091 :manpage:`times(2)` and :manpage:`times(3)` manual page on Unix or `the GetProcessTimes MSDN
Roger Hurwitz37c55b22020-02-10 14:50:19 -08004092 <https://docs.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes>`_
4093 on Windows. On Windows, only :attr:`user` and :attr:`system` are known; the other attributes are zero.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004094
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004095 .. availability:: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00004096
Larry Hastings605a62d2012-06-24 04:33:36 -07004097 .. versionchanged:: 3.3
4098 Return type changed from a tuple to a tuple-like object
4099 with named attributes.
4100
Georg Brandl116aa622007-08-15 14:28:22 +00004101
4102.. function:: wait()
4103
4104 Wait for completion of a child process, and return a tuple containing its pid
4105 and exit status indication: a 16-bit number, whose low byte is the signal number
4106 that killed the process, and whose high byte is the exit status (if the signal
4107 number is zero); the high bit of the low byte is set if a core file was
Benjamin Petersonf650e462010-05-06 23:03:05 +00004108 produced.
4109
Victor Stinner65a796e2020-04-01 18:49:29 +02004110 :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
4111 exit code.
4112
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004113 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004114
Victor Stinner65a796e2020-04-01 18:49:29 +02004115 .. seealso::
4116
4117 :func:`waitpid` can be used to wait for the completion of a specific
4118 child process and has more options.
4119
Ross Lagerwall7807c352011-03-17 20:20:30 +02004120.. function:: waitid(idtype, id, options)
4121
4122 Wait for the completion of one or more child processes.
Benjamin Peterson5c0c3252019-11-05 21:58:31 -08004123 *idtype* can be :data:`P_PID`, :data:`P_PGID`, :data:`P_ALL`, or
4124 :data:`P_PIDFD` on Linux.
Ross Lagerwall7807c352011-03-17 20:20:30 +02004125 *id* specifies the pid to wait on.
4126 *options* is constructed from the ORing of one or more of :data:`WEXITED`,
4127 :data:`WSTOPPED` or :data:`WCONTINUED` and additionally may be ORed with
4128 :data:`WNOHANG` or :data:`WNOWAIT`. The return value is an object
4129 representing the data contained in the :c:type:`siginfo_t` structure, namely:
4130 :attr:`si_pid`, :attr:`si_uid`, :attr:`si_signo`, :attr:`si_status`,
4131 :attr:`si_code` or ``None`` if :data:`WNOHANG` is specified and there are no
4132 children in a waitable state.
4133
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004134 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02004135
4136 .. versionadded:: 3.3
4137
4138.. data:: P_PID
4139 P_PGID
4140 P_ALL
4141
4142 These are the possible values for *idtype* in :func:`waitid`. They affect
4143 how *id* is interpreted.
4144
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004145 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02004146
4147 .. versionadded:: 3.3
4148
Benjamin Peterson5c0c3252019-11-05 21:58:31 -08004149.. data:: P_PIDFD
4150
4151 This is a Linux-specific *idtype* that indicates that *id* is a file
4152 descriptor that refers to a process.
4153
4154 .. availability:: Linux 5.4+
4155
4156 .. versionadded:: 3.9
4157
Ross Lagerwall7807c352011-03-17 20:20:30 +02004158.. data:: WEXITED
4159 WSTOPPED
4160 WNOWAIT
4161
4162 Flags that can be used in *options* in :func:`waitid` that specify what
4163 child signal to wait for.
4164
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004165 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02004166
4167 .. versionadded:: 3.3
4168
4169
4170.. data:: CLD_EXITED
Dong-hee Na2eba6ad2019-10-21 16:01:05 +09004171 CLD_KILLED
Ross Lagerwall7807c352011-03-17 20:20:30 +02004172 CLD_DUMPED
4173 CLD_TRAPPED
Dong-hee Na2eba6ad2019-10-21 16:01:05 +09004174 CLD_STOPPED
Ross Lagerwall7807c352011-03-17 20:20:30 +02004175 CLD_CONTINUED
4176
4177 These are the possible values for :attr:`si_code` in the result returned by
4178 :func:`waitid`.
4179
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004180 .. availability:: Unix.
Ross Lagerwall7807c352011-03-17 20:20:30 +02004181
4182 .. versionadded:: 3.3
4183
Dong-hee Na2eba6ad2019-10-21 16:01:05 +09004184 .. versionchanged:: 3.9
4185 Added :data:`CLD_KILLED` and :data:`CLD_STOPPED` values.
4186
Georg Brandl116aa622007-08-15 14:28:22 +00004187
4188.. function:: waitpid(pid, options)
4189
4190 The details of this function differ on Unix and Windows.
4191
4192 On Unix: Wait for completion of a child process given by process id *pid*, and
4193 return a tuple containing its process id and exit status indication (encoded as
4194 for :func:`wait`). The semantics of the call are affected by the value of the
4195 integer *options*, which should be ``0`` for normal operation.
4196
4197 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
4198 that specific process. If *pid* is ``0``, the request is for the status of any
4199 child in the process group of the current process. If *pid* is ``-1``, the
4200 request pertains to any child of the current process. If *pid* is less than
4201 ``-1``, status is requested for any process in the process group ``-pid`` (the
4202 absolute value of *pid*).
4203
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00004204 An :exc:`OSError` is raised with the value of errno when the syscall
4205 returns -1.
4206
Georg Brandl116aa622007-08-15 14:28:22 +00004207 On Windows: Wait for completion of a process given by process handle *pid*, and
4208 return a tuple containing *pid*, and its exit status shifted left by 8 bits
4209 (shifting makes cross-platform use of the function easier). A *pid* less than or
4210 equal to ``0`` has no special meaning on Windows, and raises an exception. The
4211 value of integer *options* has no effect. *pid* can refer to any process whose
Serhiy Storchakadab83542013-10-13 20:12:43 +03004212 id is known, not necessarily a child process. The :func:`spawn\* <spawnl>`
4213 functions called with :const:`P_NOWAIT` return suitable process handles.
Georg Brandl116aa622007-08-15 14:28:22 +00004214
Victor Stinner65a796e2020-04-01 18:49:29 +02004215 :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
4216 exit code.
4217
Victor Stinnera766ddf2015-03-26 23:50:57 +01004218 .. versionchanged:: 3.5
Victor Stinner708d9ba2015-04-02 11:49:42 +02004219 If the system call is interrupted and the signal handler does not raise an
Victor Stinnera766ddf2015-03-26 23:50:57 +01004220 exception, the function now retries the system call instead of raising an
4221 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
4222
Georg Brandl116aa622007-08-15 14:28:22 +00004223
Ezio Melottiba4d8ed2012-11-23 19:45:52 +02004224.. function:: wait3(options)
Georg Brandl116aa622007-08-15 14:28:22 +00004225
4226 Similar to :func:`waitpid`, except no process id argument is given and a
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +02004227 3-element tuple containing the child's process id, exit status indication,
4228 and resource usage information is returned. Refer to
4229 :mod:`resource`.\ :func:`~resource.getrusage` for details on resource usage
4230 information. The option argument is the same as that provided to
4231 :func:`waitpid` and :func:`wait4`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004232
Victor Stinner65a796e2020-04-01 18:49:29 +02004233 :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
4234 exitcode.
4235
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004236 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004237
Georg Brandl116aa622007-08-15 14:28:22 +00004238
Victor Stinner4195b5c2012-02-08 23:03:19 +01004239.. function:: wait4(pid, options)
Georg Brandl116aa622007-08-15 14:28:22 +00004240
4241 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
4242 process id, exit status indication, and resource usage information is returned.
Serhiy Storchakadab83542013-10-13 20:12:43 +03004243 Refer to :mod:`resource`.\ :func:`~resource.getrusage` for details on
4244 resource usage information. The arguments to :func:`wait4` are the same
4245 as those provided to :func:`waitpid`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004246
Victor Stinner65a796e2020-04-01 18:49:29 +02004247 :func:`waitstatus_to_exitcode` can be used to convert the exit status into an
4248 exitcode.
4249
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004250 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004251
Georg Brandl116aa622007-08-15 14:28:22 +00004252
Victor Stinner65a796e2020-04-01 18:49:29 +02004253.. function:: waitstatus_to_exitcode(status)
4254
4255 Convert a wait status to an exit code.
4256
4257 On Unix:
4258
4259 * If the process exited normally (if ``WIFEXITED(status)`` is true),
4260 return the process exit status (return ``WEXITSTATUS(status)``):
4261 result greater than or equal to 0.
4262 * If the process was terminated by a signal (if ``WIFSIGNALED(status)`` is
4263 true), return ``-signum`` where *signum* is the number of the signal that
4264 caused the process to terminate (return ``-WTERMSIG(status)``):
4265 result less than 0.
4266 * Otherwise, raise a :exc:`ValueError`.
4267
4268 On Windows, return *status* shifted right by 8 bits.
4269
4270 On Unix, if the process is being traced or if :func:`waitpid` was called
4271 with :data:`WUNTRACED` option, the caller must first check if
4272 ``WIFSTOPPED(status)`` is true. This function must not be called if
4273 ``WIFSTOPPED(status)`` is true.
4274
4275 .. seealso::
4276
4277 :func:`WIFEXITED`, :func:`WEXITSTATUS`, :func:`WIFSIGNALED`,
4278 :func:`WTERMSIG`, :func:`WIFSTOPPED`, :func:`WSTOPSIG` functions.
4279
4280 .. versionadded:: 3.9
4281
4282
Georg Brandl116aa622007-08-15 14:28:22 +00004283.. data:: WNOHANG
4284
4285 The option for :func:`waitpid` to return immediately if no child process status
4286 is available immediately. The function returns ``(0, 0)`` in this case.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004287
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004288 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004289
4290
4291.. data:: WCONTINUED
4292
4293 This option causes child processes to be reported if they have been continued
Benjamin Petersonf650e462010-05-06 23:03:05 +00004294 from a job control stop since their status was last reported.
4295
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004296 .. availability:: some Unix systems.
Georg Brandl116aa622007-08-15 14:28:22 +00004297
Georg Brandl116aa622007-08-15 14:28:22 +00004298
4299.. data:: WUNTRACED
4300
4301 This option causes child processes to be reported if they have been stopped but
Benjamin Petersonf650e462010-05-06 23:03:05 +00004302 their current state has not been reported since they were stopped.
4303
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004304 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004305
Georg Brandl116aa622007-08-15 14:28:22 +00004306
4307The following functions take a process status code as returned by
4308:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
4309used to determine the disposition of a process.
4310
Georg Brandl116aa622007-08-15 14:28:22 +00004311.. function:: WCOREDUMP(status)
4312
Christian Heimesfaf2f632008-01-06 16:59:19 +00004313 Return ``True`` if a core dump was generated for the process, otherwise
Benjamin Petersonf650e462010-05-06 23:03:05 +00004314 return ``False``.
4315
Victor Stinner7c723832020-04-01 15:48:05 +02004316 This function should be employed only if :func:`WIFSIGNALED` is true.
4317
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004318 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004319
Georg Brandl116aa622007-08-15 14:28:22 +00004320
4321.. function:: WIFCONTINUED(status)
4322
Victor Stinner7c723832020-04-01 15:48:05 +02004323 Return ``True`` if a stopped child has been resumed by delivery of
4324 :data:`~signal.SIGCONT` (if the process has been continued from a job
4325 control stop), otherwise return ``False``.
4326
4327 See :data:`WCONTINUED` option.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004328
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004329 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004330
Georg Brandl116aa622007-08-15 14:28:22 +00004331
4332.. function:: WIFSTOPPED(status)
4333
Victor Stinner7c723832020-04-01 15:48:05 +02004334 Return ``True`` if the process was stopped by delivery of a signal,
4335 otherwise return ``False``.
4336
4337 :func:`WIFSTOPPED` only returns ``True`` if the :func:`waitpid` call was
4338 done using :data:`WUNTRACED` option or when the process is being traced (see
4339 :manpage:`ptrace(2)`).
Benjamin Petersonf650e462010-05-06 23:03:05 +00004340
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004341 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004342
Georg Brandl116aa622007-08-15 14:28:22 +00004343.. function:: WIFSIGNALED(status)
4344
Victor Stinner7c723832020-04-01 15:48:05 +02004345 Return ``True`` if the process was terminated by a signal, otherwise return
Benjamin Petersonf650e462010-05-06 23:03:05 +00004346 ``False``.
4347
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004348 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004349
4350
4351.. function:: WIFEXITED(status)
4352
Victor Stinner7c723832020-04-01 15:48:05 +02004353 Return ``True`` if the process exited terminated normally, that is,
4354 by calling ``exit()`` or ``_exit()``, or by returning from ``main()``;
Benjamin Petersonf650e462010-05-06 23:03:05 +00004355 otherwise return ``False``.
4356
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004357 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004358
4359
4360.. function:: WEXITSTATUS(status)
4361
Victor Stinner7c723832020-04-01 15:48:05 +02004362 Return the process exit status.
4363
4364 This function should be employed only if :func:`WIFEXITED` is true.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004365
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004366 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004367
4368
4369.. function:: WSTOPSIG(status)
4370
Benjamin Petersonf650e462010-05-06 23:03:05 +00004371 Return the signal which caused the process to stop.
4372
Victor Stinner7c723832020-04-01 15:48:05 +02004373 This function should be employed only if :func:`WIFSTOPPED` is true.
4374
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004375 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004376
4377
4378.. function:: WTERMSIG(status)
4379
Victor Stinner7c723832020-04-01 15:48:05 +02004380 Return the number of the signal that caused the process to terminate.
4381
4382 This function should be employed only if :func:`WIFSIGNALED` is true.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004383
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004384 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004385
4386
Benjamin Peterson94b580d2011-08-02 17:30:04 -05004387Interface to the scheduler
4388--------------------------
4389
4390These functions control how a process is allocated CPU time by the operating
4391system. They are only available on some Unix platforms. For more detailed
4392information, consult your Unix manpages.
4393
4394.. versionadded:: 3.3
4395
Andrew Kuchling4921a082013-06-21 11:49:57 -04004396The following scheduling policies are exposed if they are supported by the
Benjamin Peterson94b580d2011-08-02 17:30:04 -05004397operating system.
4398
4399.. data:: SCHED_OTHER
4400
4401 The default scheduling policy.
4402
4403.. data:: SCHED_BATCH
4404
4405 Scheduling policy for CPU-intensive processes that tries to preserve
4406 interactivity on the rest of the computer.
4407
4408.. data:: SCHED_IDLE
4409
4410 Scheduling policy for extremely low priority background tasks.
4411
4412.. data:: SCHED_SPORADIC
4413
4414 Scheduling policy for sporadic server programs.
4415
4416.. data:: SCHED_FIFO
4417
4418 A First In First Out scheduling policy.
4419
4420.. data:: SCHED_RR
4421
4422 A round-robin scheduling policy.
4423
4424.. data:: SCHED_RESET_ON_FORK
4425
Martin Panter8d56c022016-05-29 04:13:35 +00004426 This flag can be OR'ed with any other scheduling policy. When a process with
Benjamin Peterson94b580d2011-08-02 17:30:04 -05004427 this flag set forks, its child's scheduling policy and priority are reset to
4428 the default.
4429
4430
4431.. class:: sched_param(sched_priority)
4432
4433 This class represents tunable scheduling parameters used in
4434 :func:`sched_setparam`, :func:`sched_setscheduler`, and
4435 :func:`sched_getparam`. It is immutable.
4436
4437 At the moment, there is only one possible parameter:
4438
4439 .. attribute:: sched_priority
4440
4441 The scheduling priority for a scheduling policy.
4442
4443
4444.. function:: sched_get_priority_min(policy)
4445
4446 Get the minimum priority value for *policy*. *policy* is one of the
4447 scheduling policy constants above.
4448
4449
4450.. function:: sched_get_priority_max(policy)
4451
4452 Get the maximum priority value for *policy*. *policy* is one of the
4453 scheduling policy constants above.
4454
4455
4456.. function:: sched_setscheduler(pid, policy, param)
4457
4458 Set the scheduling policy for the process with PID *pid*. A *pid* of 0 means
4459 the calling process. *policy* is one of the scheduling policy constants
4460 above. *param* is a :class:`sched_param` instance.
4461
4462
4463.. function:: sched_getscheduler(pid)
4464
4465 Return the scheduling policy for the process with PID *pid*. A *pid* of 0
4466 means the calling process. The result is one of the scheduling policy
4467 constants above.
4468
4469
4470.. function:: sched_setparam(pid, param)
4471
4472 Set a scheduling parameters for the process with PID *pid*. A *pid* of 0 means
4473 the calling process. *param* is a :class:`sched_param` instance.
4474
4475
4476.. function:: sched_getparam(pid)
4477
4478 Return the scheduling parameters as a :class:`sched_param` instance for the
4479 process with PID *pid*. A *pid* of 0 means the calling process.
4480
4481
4482.. function:: sched_rr_get_interval(pid)
4483
4484 Return the round-robin quantum in seconds for the process with PID *pid*. A
4485 *pid* of 0 means the calling process.
4486
4487
4488.. function:: sched_yield()
4489
4490 Voluntarily relinquish the CPU.
4491
4492
Benjamin Peterson94b580d2011-08-02 17:30:04 -05004493.. function:: sched_setaffinity(pid, mask)
4494
Antoine Pitrou84869872012-08-04 16:16:35 +02004495 Restrict the process with PID *pid* (or the current process if zero) to a
4496 set of CPUs. *mask* is an iterable of integers representing the set of
4497 CPUs to which the process should be restricted.
Benjamin Peterson94b580d2011-08-02 17:30:04 -05004498
4499
Antoine Pitrou84869872012-08-04 16:16:35 +02004500.. function:: sched_getaffinity(pid)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05004501
Antoine Pitrou84869872012-08-04 16:16:35 +02004502 Return the set of CPUs the process with PID *pid* (or the current process
4503 if zero) is restricted to.
Benjamin Peterson94b580d2011-08-02 17:30:04 -05004504
4505
Georg Brandl116aa622007-08-15 14:28:22 +00004506.. _os-path:
4507
4508Miscellaneous System Information
4509--------------------------------
4510
4511
4512.. function:: confstr(name)
4513
4514 Return string-valued system configuration values. *name* specifies the
4515 configuration value to retrieve; it may be a string which is the name of a
4516 defined system value; these names are specified in a number of standards (POSIX,
4517 Unix 95, Unix 98, and others). Some platforms define additional names as well.
4518 The names known to the host operating system are given as the keys of the
4519 ``confstr_names`` dictionary. For configuration variables not included in that
Benjamin Petersonf650e462010-05-06 23:03:05 +00004520 mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00004521
4522 If the configuration value specified by *name* isn't defined, ``None`` is
4523 returned.
4524
4525 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
4526 specific value for *name* is not supported by the host system, even if it is
4527 included in ``confstr_names``, an :exc:`OSError` is raised with
4528 :const:`errno.EINVAL` for the error number.
4529
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004530 .. availability:: Unix.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004531
Georg Brandl116aa622007-08-15 14:28:22 +00004532
4533.. data:: confstr_names
4534
4535 Dictionary mapping names accepted by :func:`confstr` to the integer values
4536 defined for those names by the host operating system. This can be used to
Benjamin Petersonf650e462010-05-06 23:03:05 +00004537 determine the set of names known to the system.
4538
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004539 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004540
4541
Charles-Francois Natali44feda32013-05-20 14:40:46 +02004542.. function:: cpu_count()
4543
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03004544 Return the number of CPUs in the system. Returns ``None`` if undetermined.
Charles-Francois Natali44feda32013-05-20 14:40:46 +02004545
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01004546 This number is not equivalent to the number of CPUs the current process can
4547 use. The number of usable CPUs can be obtained with
4548 ``len(os.sched_getaffinity(0))``
4549
4550
Charles-Francois Natali44feda32013-05-20 14:40:46 +02004551 .. versionadded:: 3.4
4552
4553
Georg Brandl116aa622007-08-15 14:28:22 +00004554.. function:: getloadavg()
4555
Christian Heimesa62da1d2008-01-12 19:39:10 +00004556 Return the number of processes in the system run queue averaged over the last
4557 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Benjamin Petersonf650e462010-05-06 23:03:05 +00004558 unobtainable.
4559
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004560 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004561
Georg Brandl116aa622007-08-15 14:28:22 +00004562
4563.. function:: sysconf(name)
4564
4565 Return integer-valued system configuration values. If the configuration value
4566 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
4567 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
4568 provides information on the known names is given by ``sysconf_names``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00004569
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004570 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004571
4572
4573.. data:: sysconf_names
4574
4575 Dictionary mapping names accepted by :func:`sysconf` to the integer values
4576 defined for those names by the host operating system. This can be used to
Benjamin Petersonf650e462010-05-06 23:03:05 +00004577 determine the set of names known to the system.
4578
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004579 .. availability:: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00004580
Christian Heimesfaf2f632008-01-06 16:59:19 +00004581The following data values are used to support path manipulation operations. These
Georg Brandl116aa622007-08-15 14:28:22 +00004582are defined for all platforms.
4583
4584Higher-level operations on pathnames are defined in the :mod:`os.path` module.
4585
4586
Serhiy Storchaka913876d2018-10-28 13:41:26 +02004587.. index:: single: . (dot); in pathnames
Georg Brandl116aa622007-08-15 14:28:22 +00004588.. data:: curdir
4589
4590 The constant string used by the operating system to refer to the current
Georg Brandlc575c902008-09-13 17:46:05 +00004591 directory. This is ``'.'`` for Windows and POSIX. Also available via
4592 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00004593
4594
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03004595.. index:: single: ..; in pathnames
Georg Brandl116aa622007-08-15 14:28:22 +00004596.. data:: pardir
4597
4598 The constant string used by the operating system to refer to the parent
Georg Brandlc575c902008-09-13 17:46:05 +00004599 directory. This is ``'..'`` for Windows and POSIX. Also available via
4600 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00004601
4602
Serhiy Storchaka913876d2018-10-28 13:41:26 +02004603.. index:: single: / (slash); in pathnames
4604.. index:: single: \ (backslash); in pathnames (Windows)
Georg Brandl116aa622007-08-15 14:28:22 +00004605.. data:: sep
4606
Georg Brandlc575c902008-09-13 17:46:05 +00004607 The character used by the operating system to separate pathname components.
4608 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
4609 is not sufficient to be able to parse or concatenate pathnames --- use
Georg Brandl116aa622007-08-15 14:28:22 +00004610 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
4611 useful. Also available via :mod:`os.path`.
4612
4613
Serhiy Storchaka913876d2018-10-28 13:41:26 +02004614.. index:: single: / (slash); in pathnames
Georg Brandl116aa622007-08-15 14:28:22 +00004615.. data:: altsep
4616
4617 An alternative character used by the operating system to separate pathname
4618 components, or ``None`` if only one separator character exists. This is set to
4619 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
4620 :mod:`os.path`.
4621
4622
Serhiy Storchaka913876d2018-10-28 13:41:26 +02004623.. index:: single: . (dot); in pathnames
Georg Brandl116aa622007-08-15 14:28:22 +00004624.. data:: extsep
4625
4626 The character which separates the base filename from the extension; for example,
4627 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
4628
Georg Brandl116aa622007-08-15 14:28:22 +00004629
Serhiy Storchaka913876d2018-10-28 13:41:26 +02004630.. index:: single: : (colon); path separator (POSIX)
4631 single: ; (semicolon)
Georg Brandl116aa622007-08-15 14:28:22 +00004632.. data:: pathsep
4633
4634 The character conventionally used by the operating system to separate search
4635 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
4636 Windows. Also available via :mod:`os.path`.
4637
4638
4639.. data:: defpath
4640
Serhiy Storchakadab83542013-10-13 20:12:43 +03004641 The default search path used by :func:`exec\*p\* <execl>` and
4642 :func:`spawn\*p\* <spawnl>` if the environment doesn't have a ``'PATH'``
4643 key. Also available via :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00004644
4645
4646.. data:: linesep
4647
4648 The string used to separate (or, rather, terminate) lines on the current
Georg Brandlc575c902008-09-13 17:46:05 +00004649 platform. This may be a single character, such as ``'\n'`` for POSIX, or
4650 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
4651 *os.linesep* as a line terminator when writing files opened in text mode (the
4652 default); use a single ``'\n'`` instead, on all platforms.
Georg Brandl116aa622007-08-15 14:28:22 +00004653
4654
4655.. data:: devnull
4656
Georg Brandl850a9902010-05-21 22:04:32 +00004657 The file path of the null device. For example: ``'/dev/null'`` for
4658 POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00004659
Andrew Kuchling4921a082013-06-21 11:49:57 -04004660.. data:: RTLD_LAZY
4661 RTLD_NOW
4662 RTLD_GLOBAL
4663 RTLD_LOCAL
4664 RTLD_NODELETE
4665 RTLD_NOLOAD
4666 RTLD_DEEPBIND
4667
4668 Flags for use with the :func:`~sys.setdlopenflags` and
4669 :func:`~sys.getdlopenflags` functions. See the Unix manual page
4670 :manpage:`dlopen(3)` for what the different flags mean.
4671
4672 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +00004673
Georg Brandl116aa622007-08-15 14:28:22 +00004674
Victor Stinner9b1f4742016-09-06 16:18:52 -07004675Random numbers
4676--------------
Georg Brandl116aa622007-08-15 14:28:22 +00004677
4678
Victor Stinner9b1f4742016-09-06 16:18:52 -07004679.. function:: getrandom(size, flags=0)
Georg Brandl116aa622007-08-15 14:28:22 +00004680
Victor Stinner9b1f4742016-09-06 16:18:52 -07004681 Get up to *size* random bytes. The function can return less bytes than
4682 requested.
4683
4684 These bytes can be used to seed user-space random number generators or for
4685 cryptographic purposes.
4686
4687 ``getrandom()`` relies on entropy gathered from device drivers and other
4688 sources of environmental noise. Unnecessarily reading large quantities of
4689 data will have a negative impact on other users of the ``/dev/random`` and
4690 ``/dev/urandom`` devices.
4691
4692 The flags argument is a bit mask that can contain zero or more of the
4693 following values ORed together: :py:data:`os.GRND_RANDOM` and
4694 :py:data:`GRND_NONBLOCK`.
4695
4696 See also the `Linux getrandom() manual page
4697 <http://man7.org/linux/man-pages/man2/getrandom.2.html>`_.
4698
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04004699 .. availability:: Linux 3.17 and newer.
Victor Stinner9b1f4742016-09-06 16:18:52 -07004700
4701 .. versionadded:: 3.6
4702
4703.. function:: urandom(size)
4704
4705 Return a string of *size* random bytes suitable for cryptographic use.
Georg Brandl116aa622007-08-15 14:28:22 +00004706
4707 This function returns random bytes from an OS-specific randomness source. The
4708 returned data should be unpredictable enough for cryptographic applications,
Victor Stinnerdddf4842016-06-07 11:21:42 +02004709 though its exact quality depends on the OS implementation.
4710
Victor Stinnere66987e2016-09-06 16:33:52 -07004711 On Linux, if the ``getrandom()`` syscall is available, it is used in
4712 blocking mode: block until the system urandom entropy pool is initialized
4713 (128 bits of entropy are collected by the kernel). See the :pep:`524` for
4714 the rationale. On Linux, the :func:`getrandom` function can be used to get
4715 random bytes in non-blocking mode (using the :data:`GRND_NONBLOCK` flag) or
4716 to poll until the system urandom entropy pool is initialized.
Andrew Svetlov03cb99c2012-10-16 13:15:06 +03004717
Victor Stinnere66987e2016-09-06 16:33:52 -07004718 On a Unix-like system, random bytes are read from the ``/dev/urandom``
4719 device. If the ``/dev/urandom`` device is not available or not readable, the
4720 :exc:`NotImplementedError` exception is raised.
4721
4722 On Windows, it will use ``CryptGenRandom()``.
4723
4724 .. seealso::
4725 The :mod:`secrets` module provides higher level functions. For an
4726 easy-to-use interface to the random number generator provided by your
4727 platform, please see :class:`random.SystemRandom`.
4728
4729 .. versionchanged:: 3.6.0
4730 On Linux, ``getrandom()`` is now used in blocking mode to increase the
4731 security.
Victor Stinnerace88482015-07-29 02:28:32 +02004732
Victor Stinnerdddf4842016-06-07 11:21:42 +02004733 .. versionchanged:: 3.5.2
Victor Stinner9b1f4742016-09-06 16:18:52 -07004734 On Linux, if the ``getrandom()`` syscall blocks (the urandom entropy pool
4735 is not initialized yet), fall back on reading ``/dev/urandom``.
Victor Stinnerdddf4842016-06-07 11:21:42 +02004736
Victor Stinnerace88482015-07-29 02:28:32 +02004737 .. versionchanged:: 3.5
4738 On Linux 3.17 and newer, the ``getrandom()`` syscall is now used
4739 when available. On OpenBSD 5.6 and newer, the C ``getentropy()``
4740 function is now used. These functions avoid the usage of an internal file
4741 descriptor.
Victor Stinner9b1f4742016-09-06 16:18:52 -07004742
4743.. data:: GRND_NONBLOCK
4744
4745 By default, when reading from ``/dev/random``, :func:`getrandom` blocks if
4746 no random bytes are available, and when reading from ``/dev/urandom``, it blocks
4747 if the entropy pool has not yet been initialized.
4748
4749 If the :py:data:`GRND_NONBLOCK` flag is set, then :func:`getrandom` does not
4750 block in these cases, but instead immediately raises :exc:`BlockingIOError`.
4751
4752 .. versionadded:: 3.6
4753
4754.. data:: GRND_RANDOM
4755
4756 If this bit is set, then random bytes are drawn from the
4757 ``/dev/random`` pool instead of the ``/dev/urandom`` pool.
4758
4759 .. versionadded:: 3.6