blob: 5073e7a5de15427d15633a31303df3c6cee28525 [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
7
Christian Heimesa62da1d2008-01-12 19:39:10 +00008This module provides a portable way of using operating system dependent
9functionality. If you just want to read or write a file see :func:`open`, if
10you want to manipulate paths, see the :mod:`os.path` module, and if you want to
11read all the lines in all the files on the command line see the :mod:`fileinput`
12module. For creating temporary files and directories see the :mod:`tempfile`
13module, and for high-level file and directory handling see the :mod:`shutil`
14module.
Georg Brandl116aa622007-08-15 14:28:22 +000015
Benjamin Peterson1baf4652009-12-31 03:11:23 +000016Notes on the availability of these functions:
Georg Brandl116aa622007-08-15 14:28:22 +000017
Benjamin Peterson1baf4652009-12-31 03:11:23 +000018* The design of all built-in operating system dependent modules of Python is
19 such that as long as the same functionality is available, it uses the same
20 interface; for example, the function ``os.stat(path)`` returns stat
21 information about *path* in the same format (which happens to have originated
22 with the POSIX interface).
Georg Brandl116aa622007-08-15 14:28:22 +000023
Benjamin Peterson1baf4652009-12-31 03:11:23 +000024* Extensions peculiar to a particular operating system are also available
25 through the :mod:`os` module, but using them is of course a threat to
26 portability.
Georg Brandl116aa622007-08-15 14:28:22 +000027
Benjamin Peterson1baf4652009-12-31 03:11:23 +000028* All functions accepting path or file names accept both bytes and string
29 objects, and result in an object of the same type, if a path or file name is
30 returned.
Georg Brandl76e55382008-10-08 16:34:57 +000031
Benjamin Peterson1baf4652009-12-31 03:11:23 +000032* An "Availability: Unix" note means that this function is commonly found on
33 Unix systems. It does not make any claims about its existence on a specific
34 operating system.
35
36* If not separately noted, all functions that claim "Availability: Unix" are
37 supported on Mac OS X, which builds on a Unix core.
38
Benjamin Petersonf650e462010-05-06 23:03:05 +000039.. Availability notes get their own line and occur at the end of the function
40.. documentation.
41
Georg Brandlc575c902008-09-13 17:46:05 +000042.. note::
43
Christian Heimesa62da1d2008-01-12 19:39:10 +000044 All functions in this module raise :exc:`OSError` in the case of invalid or
45 inaccessible file names and paths, or other arguments that have the correct
46 type, but are not accepted by the operating system.
Georg Brandl116aa622007-08-15 14:28:22 +000047
Georg Brandl116aa622007-08-15 14:28:22 +000048.. exception:: error
49
Christian Heimesa62da1d2008-01-12 19:39:10 +000050 An alias for the built-in :exc:`OSError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +000051
52
53.. data:: name
54
Benjamin Peterson1baf4652009-12-31 03:11:23 +000055 The name of the operating system dependent module imported. The following
Ned Deily5c867012014-06-26 23:40:06 -070056 names have currently been registered: ``'posix'``, ``'nt'``,
Jesus Ceaf6c2e892012-10-05 01:11:10 +020057 ``'ce'``, ``'java'``.
Georg Brandl116aa622007-08-15 14:28:22 +000058
Antoine Pitroua83cdaa2011-07-09 15:54:23 +020059 .. seealso::
60 :attr:`sys.platform` has a finer granularity. :func:`os.uname` gives
61 system-dependent version information.
62
63 The :mod:`platform` module provides detailed checks for the
64 system's identity.
65
Georg Brandl116aa622007-08-15 14:28:22 +000066
Martin v. Löwis011e8422009-05-05 04:43:17 +000067.. _os-filenames:
Victor Stinner6bfd8542014-06-19 12:50:27 +020068.. _filesystem-encoding:
Martin v. Löwis011e8422009-05-05 04:43:17 +000069
70File Names, Command Line Arguments, and Environment Variables
71-------------------------------------------------------------
72
Georg Brandl67b21b72010-08-17 15:07:14 +000073In Python, file names, command line arguments, and environment variables are
74represented using the string type. On some systems, decoding these strings to
75and from bytes is necessary before passing them to the operating system. Python
76uses the file system encoding to perform this conversion (see
77:func:`sys.getfilesystemencoding`).
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
Georg Brandl67b21b72010-08-17 15:07:14 +000087The file system encoding must guarantee to successfully decode all bytes
88below 128. If the file system encoding fails to provide this guarantee, API
89functions may raise UnicodeErrors.
Martin v. Löwis011e8422009-05-05 04:43:17 +000090
91
Georg Brandl116aa622007-08-15 14:28:22 +000092.. _os-procinfo:
93
94Process Parameters
95------------------
96
97These functions and data items provide information and operate on the current
98process and user.
99
100
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200101.. function:: ctermid()
102
103 Return the filename corresponding to the controlling terminal of the process.
104
105 Availability: Unix.
106
107
Georg Brandl116aa622007-08-15 14:28:22 +0000108.. data:: environ
109
Chris Jerdonek11f3f172012-11-03 12:05:55 -0700110 A :term:`mapping` object representing the string environment. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000111 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
112 and is equivalent to ``getenv("HOME")`` in C.
113
114 This mapping is captured the first time the :mod:`os` module is imported,
115 typically during Python startup as part of processing :file:`site.py`. Changes
116 to the environment made after this time are not reflected in ``os.environ``,
117 except for changes made by modifying ``os.environ`` directly.
118
119 If the platform supports the :func:`putenv` function, this mapping may be used
120 to modify the environment as well as query the environment. :func:`putenv` will
121 be called automatically when the mapping is modified.
122
Victor Stinner84ae1182010-05-06 22:05:07 +0000123 On Unix, keys and values use :func:`sys.getfilesystemencoding` and
124 ``'surrogateescape'`` error handler. Use :data:`environb` if you would like
125 to use a different encoding.
126
Georg Brandl116aa622007-08-15 14:28:22 +0000127 .. note::
128
129 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
130 to modify ``os.environ``.
131
132 .. note::
133
Georg Brandlc575c902008-09-13 17:46:05 +0000134 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
135 cause memory leaks. Refer to the system documentation for
Georg Brandl60203b42010-10-06 10:11:56 +0000136 :c:func:`putenv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138 If :func:`putenv` is not provided, a modified copy of this mapping may be
139 passed to the appropriate process-creation functions to cause child processes
140 to use a modified environment.
141
Georg Brandl9afde1c2007-11-01 20:32:30 +0000142 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl116aa622007-08-15 14:28:22 +0000143 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl9afde1c2007-11-01 20:32:30 +0000144 automatically when an item is deleted from ``os.environ``, and when
145 one of the :meth:`pop` or :meth:`clear` methods is called.
146
Georg Brandl116aa622007-08-15 14:28:22 +0000147
Victor Stinner84ae1182010-05-06 22:05:07 +0000148.. data:: environb
149
Chris Jerdonek11f3f172012-11-03 12:05:55 -0700150 Bytes version of :data:`environ`: a :term:`mapping` object representing the
Victor Stinner84ae1182010-05-06 22:05:07 +0000151 environment as byte strings. :data:`environ` and :data:`environb` are
152 synchronized (modify :data:`environb` updates :data:`environ`, and vice
153 versa).
154
Victor Stinnerb745a742010-05-18 17:17:23 +0000155 :data:`environb` is only available if :data:`supports_bytes_environ` is
156 True.
Victor Stinner84ae1182010-05-06 22:05:07 +0000157
Benjamin Peterson662c74f2010-05-06 22:09:03 +0000158 .. versionadded:: 3.2
159
Victor Stinner84ae1182010-05-06 22:05:07 +0000160
Georg Brandl116aa622007-08-15 14:28:22 +0000161.. function:: chdir(path)
162 fchdir(fd)
163 getcwd()
164 :noindex:
165
166 These functions are described in :ref:`os-file-dir`.
167
168
Victor Stinnere8d51452010-08-19 01:05:19 +0000169.. function:: fsencode(filename)
Victor Stinner449c4662010-05-08 11:10:09 +0000170
Victor Stinnere8d51452010-08-19 01:05:19 +0000171 Encode *filename* to the filesystem encoding with ``'surrogateescape'``
Victor Stinner62165d62010-10-09 10:34:37 +0000172 error handler, or ``'strict'`` on Windows; return :class:`bytes` unchanged.
Victor Stinnere8d51452010-08-19 01:05:19 +0000173
Antoine Pitroua305ca72010-09-25 22:12:00 +0000174 :func:`fsdecode` is the reverse function.
Victor Stinnere8d51452010-08-19 01:05:19 +0000175
176 .. versionadded:: 3.2
177
178
179.. function:: fsdecode(filename)
180
181 Decode *filename* from the filesystem encoding with ``'surrogateescape'``
Victor Stinner62165d62010-10-09 10:34:37 +0000182 error handler, or ``'strict'`` on Windows; return :class:`str` unchanged.
Victor Stinnere8d51452010-08-19 01:05:19 +0000183
184 :func:`fsencode` is the reverse function.
Victor Stinner449c4662010-05-08 11:10:09 +0000185
186 .. versionadded:: 3.2
187
188
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200189.. function:: getenv(key, default=None)
190
191 Return the value of the environment variable *key* if it exists, or
192 *default* if it doesn't. *key*, *default* and the result are str.
193
194 On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding`
195 and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you
196 would like to use a different encoding.
197
198 Availability: most flavors of Unix, Windows.
199
200
201.. function:: getenvb(key, default=None)
202
203 Return the value of the environment variable *key* if it exists, or
204 *default* if it doesn't. *key*, *default* and the result are bytes.
205
206 Availability: most flavors of Unix.
207
208 .. versionadded:: 3.2
209
210
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000211.. function:: get_exec_path(env=None)
212
213 Returns the list of directories that will be searched for a named
214 executable, similar to a shell, when launching a process.
215 *env*, when specified, should be an environment variable dictionary
216 to lookup the PATH in.
217 By default, when *env* is None, :data:`environ` is used.
218
219 .. versionadded:: 3.2
220
221
Georg Brandl116aa622007-08-15 14:28:22 +0000222.. function:: getegid()
223
224 Return the effective group id of the current process. This corresponds to the
Benjamin Petersonf650e462010-05-06 23:03:05 +0000225 "set id" bit on the file being executed in the current process.
226
227 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229
230.. function:: geteuid()
231
232 .. index:: single: user; effective id
233
Benjamin Petersonf650e462010-05-06 23:03:05 +0000234 Return the current process's effective user id.
235
236 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238
239.. function:: getgid()
240
241 .. index:: single: process; group
242
Benjamin Petersonf650e462010-05-06 23:03:05 +0000243 Return the real group id of the current process.
244
245 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200248.. function:: getgrouplist(user, group)
249
250 Return list of group ids that *user* belongs to. If *group* is not in the
251 list, it is included; typically, *group* is specified as the group ID
252 field from the password record for *user*.
253
254 Availability: Unix.
255
256 .. versionadded:: 3.3
257
258
Georg Brandl116aa622007-08-15 14:28:22 +0000259.. function:: getgroups()
260
261 Return list of supplemental group ids associated with the current process.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000262
Georg Brandl116aa622007-08-15 14:28:22 +0000263 Availability: Unix.
264
Larry Hastings3732ed22014-03-15 21:13:56 -0700265 .. note::
266
267 On Mac OS X, :func:`getgroups` behavior differs somewhat from
Ned Deily2e209682012-04-30 11:14:02 -0700268 other Unix platforms. If the Python interpreter was built with a
269 deployment target of :const:`10.5` or earlier, :func:`getgroups` returns
270 the list of effective group ids associated with the current user process;
271 this list is limited to a system-defined number of entries, typically 16,
272 and may be modified by calls to :func:`setgroups` if suitably privileged.
273 If built with a deployment target greater than :const:`10.5`,
274 :func:`getgroups` returns the current group access list for the user
275 associated with the effective user id of the process; the group access
276 list may change over the lifetime of the process, it is not affected by
277 calls to :func:`setgroups`, and its length is not limited to 16. The
278 deployment target value, :const:`MACOSX_DEPLOYMENT_TARGET`, can be
279 obtained with :func:`sysconfig.get_config_var`.
280
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282.. function:: getlogin()
283
284 Return the name of the user logged in on the controlling terminal of the
Benjamin Petersone218bcb2014-08-30 21:04:15 -0400285 process. For most purposes, it is more useful to use the environment
286 variables :envvar:`LOGNAME` or :envvar:`USERNAME` to find out who the user
287 is, or ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the current
288 real user id.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000289
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000290 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000291
292
293.. function:: getpgid(pid)
294
295 Return the process group id of the process with process id *pid*. If *pid* is 0,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000296 the process group id of the current process is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000297
Benjamin Petersonf650e462010-05-06 23:03:05 +0000298 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300.. function:: getpgrp()
301
302 .. index:: single: process; group
303
Benjamin Petersonf650e462010-05-06 23:03:05 +0000304 Return the id of the current process group.
305
306 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308
309.. function:: getpid()
310
311 .. index:: single: process; id
312
Benjamin Petersonf650e462010-05-06 23:03:05 +0000313 Return the current process id.
314
315 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317
318.. function:: getppid()
319
320 .. index:: single: process; id of parent
321
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000322 Return the parent's process id. When the parent process has exited, on Unix
323 the id returned is the one of the init process (1), on Windows it is still
324 the same id, which may be already reused by another process.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000325
Georg Brandl8a5555f2012-06-24 13:29:09 +0200326 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000327
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000328 .. versionchanged:: 3.2
329 Added support for Windows.
Georg Brandl1b83a452009-11-28 11:12:26 +0000330
Georg Brandl8a5555f2012-06-24 13:29:09 +0200331
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000332.. function:: getpriority(which, who)
333
334 .. index:: single: process; scheduling priority
335
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200336 Get program scheduling priority. The value *which* is one of
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000337 :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
338 is interpreted relative to *which* (a process identifier for
339 :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200340 user ID for :const:`PRIO_USER`). A zero value for *who* denotes
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000341 (respectively) the calling process, the process group of the calling process,
342 or the real user ID of the calling process.
343
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200344 Availability: Unix.
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000345
346 .. versionadded:: 3.3
347
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200348
349.. data:: PRIO_PROCESS
350 PRIO_PGRP
351 PRIO_USER
352
353 Parameters for the :func:`getpriority` and :func:`setpriority` functions.
354
355 Availability: Unix.
356
357 .. versionadded:: 3.3
358
359
Gregory P. Smithcf02c6a2009-11-27 17:54:17 +0000360.. function:: getresuid()
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000361
362 Return a tuple (ruid, euid, suid) denoting the current process's
Benjamin Petersonf650e462010-05-06 23:03:05 +0000363 real, effective, and saved user ids.
364
365 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000366
Georg Brandl1b83a452009-11-28 11:12:26 +0000367 .. versionadded:: 3.2
368
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000369
Gregory P. Smithcf02c6a2009-11-27 17:54:17 +0000370.. function:: getresgid()
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000371
372 Return a tuple (rgid, egid, sgid) denoting the current process's
Georg Brandla9b51d22010-09-05 17:07:12 +0000373 real, effective, and saved group ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000374
375 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000376
Georg Brandl1b83a452009-11-28 11:12:26 +0000377 .. versionadded:: 3.2
378
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380.. function:: getuid()
381
382 .. index:: single: user; id
383
Benjamin Peterson4bb09c82014-06-07 13:50:34 -0700384 Return the current process's real user id.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000385
386 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200389.. function:: initgroups(username, gid)
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200391 Call the system initgroups() to initialize the group access list with all of
392 the groups of which the specified username is a member, plus the specified
393 group id.
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000394
395 Availability: Unix.
396
Georg Brandl8ccadaa2012-06-24 12:50:06 +0200397 .. versionadded:: 3.2
398
Georg Brandl116aa622007-08-15 14:28:22 +0000399
Georg Brandl18244152009-09-02 20:34:52 +0000400.. function:: putenv(key, value)
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402 .. index:: single: environment variables; setting
403
Georg Brandl18244152009-09-02 20:34:52 +0000404 Set the environment variable named *key* to the string *value*. Such
Georg Brandl116aa622007-08-15 14:28:22 +0000405 changes to the environment affect subprocesses started with :func:`os.system`,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000406 :func:`popen` or :func:`fork` and :func:`execv`.
407
408 Availability: most flavors of Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410 .. note::
411
Georg Brandlc575c902008-09-13 17:46:05 +0000412 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
413 cause memory leaks. Refer to the system documentation for putenv.
Georg Brandl116aa622007-08-15 14:28:22 +0000414
415 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
416 automatically translated into corresponding calls to :func:`putenv`; however,
417 calls to :func:`putenv` don't update ``os.environ``, so it is actually
418 preferable to assign to items of ``os.environ``.
419
420
421.. function:: setegid(egid)
422
Benjamin Petersonf650e462010-05-06 23:03:05 +0000423 Set the current process's effective group id.
424
425 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427
428.. function:: seteuid(euid)
429
Benjamin Petersonf650e462010-05-06 23:03:05 +0000430 Set the current process's effective user id.
431
432 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000433
434
435.. function:: setgid(gid)
436
Benjamin Petersonf650e462010-05-06 23:03:05 +0000437 Set the current process' group id.
438
439 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441
442.. function:: setgroups(groups)
443
444 Set the list of supplemental group ids associated with the current process to
445 *groups*. *groups* must be a sequence, and each element must be an integer
Christian Heimesfaf2f632008-01-06 16:59:19 +0000446 identifying a group. This operation is typically available only to the superuser.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000447
Georg Brandl116aa622007-08-15 14:28:22 +0000448 Availability: Unix.
449
Ned Deily2e209682012-04-30 11:14:02 -0700450 .. note:: On Mac OS X, the length of *groups* may not exceed the
451 system-defined maximum number of effective group ids, typically 16.
452 See the documentation for :func:`getgroups` for cases where it may not
453 return the same group list set by calling setgroups().
Georg Brandl116aa622007-08-15 14:28:22 +0000454
455.. function:: setpgrp()
456
Andrew Svetlova2fe3342012-08-11 21:14:08 +0300457 Call the system call :c:func:`setpgrp` or ``setpgrp(0, 0)`` depending on
Georg Brandl116aa622007-08-15 14:28:22 +0000458 which version is implemented (if any). See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000459
Georg Brandl116aa622007-08-15 14:28:22 +0000460 Availability: Unix.
461
462
463.. function:: setpgid(pid, pgrp)
464
Georg Brandl60203b42010-10-06 10:11:56 +0000465 Call the system call :c:func:`setpgid` to set the process group id of the
Georg Brandl116aa622007-08-15 14:28:22 +0000466 process with id *pid* to the process group with id *pgrp*. See the Unix manual
Benjamin Petersonf650e462010-05-06 23:03:05 +0000467 for the semantics.
468
469 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000470
471
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000472.. function:: setpriority(which, who, priority)
473
474 .. index:: single: process; scheduling priority
475
476 Set program scheduling priority. The value *which* is one of
477 :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
478 is interpreted relative to *which* (a process identifier for
479 :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
480 user ID for :const:`PRIO_USER`). A zero value for *who* denotes
481 (respectively) the calling process, the process group of the calling process,
482 or the real user ID of the calling process.
483 *priority* is a value in the range -20 to 19. The default priority is 0;
484 lower priorities cause more favorable scheduling.
485
486 Availability: Unix
487
488 .. versionadded:: 3.3
489
490
Georg Brandl116aa622007-08-15 14:28:22 +0000491.. function:: setregid(rgid, egid)
492
Benjamin Petersonf650e462010-05-06 23:03:05 +0000493 Set the current process's real and effective group ids.
494
495 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000496
Georg Brandl1b83a452009-11-28 11:12:26 +0000497
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000498.. function:: setresgid(rgid, egid, sgid)
499
500 Set the current process's real, effective, and saved group ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000501
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000502 Availability: Unix.
503
Georg Brandl1b83a452009-11-28 11:12:26 +0000504 .. versionadded:: 3.2
505
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000506
507.. function:: setresuid(ruid, euid, suid)
508
509 Set the current process's real, effective, and saved user ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000510
Georg Brandl6faee4e2010-09-21 14:48:28 +0000511 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000512
Georg Brandl1b83a452009-11-28 11:12:26 +0000513 .. versionadded:: 3.2
514
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000515
516.. function:: setreuid(ruid, euid)
517
Benjamin Petersonf650e462010-05-06 23:03:05 +0000518 Set the current process's real and effective user ids.
519
520 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000521
Georg Brandl116aa622007-08-15 14:28:22 +0000522
523.. function:: getsid(pid)
524
Georg Brandl60203b42010-10-06 10:11:56 +0000525 Call the system call :c:func:`getsid`. See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000526
Georg Brandl116aa622007-08-15 14:28:22 +0000527 Availability: Unix.
528
Georg Brandl116aa622007-08-15 14:28:22 +0000529
530.. function:: setsid()
531
Georg Brandl60203b42010-10-06 10:11:56 +0000532 Call the system call :c:func:`setsid`. See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000533
Georg Brandl116aa622007-08-15 14:28:22 +0000534 Availability: Unix.
535
536
537.. function:: setuid(uid)
538
539 .. index:: single: user; id, setting
540
Benjamin Petersonf650e462010-05-06 23:03:05 +0000541 Set the current process's user id.
542
543 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000544
Georg Brandl116aa622007-08-15 14:28:22 +0000545
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000546.. placed in this section since it relates to errno.... a little weak
Georg Brandl116aa622007-08-15 14:28:22 +0000547.. function:: strerror(code)
548
549 Return the error message corresponding to the error code in *code*.
Georg Brandl60203b42010-10-06 10:11:56 +0000550 On platforms where :c:func:`strerror` returns ``NULL`` when given an unknown
Benjamin Petersonf650e462010-05-06 23:03:05 +0000551 error number, :exc:`ValueError` is raised.
552
553 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000554
555
Victor Stinnerb745a742010-05-18 17:17:23 +0000556.. data:: supports_bytes_environ
557
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200558 ``True`` if the native OS type of the environment is bytes (eg. ``False`` on
Victor Stinnerb745a742010-05-18 17:17:23 +0000559 Windows).
560
Victor Stinner8fddc9e2010-05-18 17:24:09 +0000561 .. versionadded:: 3.2
562
Victor Stinnerb745a742010-05-18 17:17:23 +0000563
Georg Brandl116aa622007-08-15 14:28:22 +0000564.. function:: umask(mask)
565
Benjamin Petersonf650e462010-05-06 23:03:05 +0000566 Set the current numeric umask and return the previous umask.
567
568 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000569
570
571.. function:: uname()
572
573 .. index::
574 single: gethostname() (in module socket)
575 single: gethostbyaddr() (in module socket)
576
Larry Hastings605a62d2012-06-24 04:33:36 -0700577 Returns information identifying the current operating system.
578 The return value is an object with five attributes:
579
580 * :attr:`sysname` - operating system name
581 * :attr:`nodename` - name of machine on network (implementation-defined)
582 * :attr:`release` - operating system release
583 * :attr:`version` - operating system version
584 * :attr:`machine` - hardware identifier
585
586 For backwards compatibility, this object is also iterable, behaving
587 like a five-tuple containing :attr:`sysname`, :attr:`nodename`,
588 :attr:`release`, :attr:`version`, and :attr:`machine`
589 in that order.
590
591 Some systems truncate :attr:`nodename` to 8 characters or to the
Georg Brandl116aa622007-08-15 14:28:22 +0000592 leading component; a better way to get the hostname is
593 :func:`socket.gethostname` or even
Benjamin Petersonf650e462010-05-06 23:03:05 +0000594 ``socket.gethostbyaddr(socket.gethostname())``.
595
596 Availability: recent flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000597
Larry Hastings605a62d2012-06-24 04:33:36 -0700598 .. versionchanged:: 3.3
599 Return type changed from a tuple to a tuple-like object
600 with named attributes.
601
Georg Brandl116aa622007-08-15 14:28:22 +0000602
Georg Brandl18244152009-09-02 20:34:52 +0000603.. function:: unsetenv(key)
Georg Brandl116aa622007-08-15 14:28:22 +0000604
605 .. index:: single: environment variables; deleting
606
Georg Brandl18244152009-09-02 20:34:52 +0000607 Unset (delete) the environment variable named *key*. Such changes to the
Georg Brandl116aa622007-08-15 14:28:22 +0000608 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
Benjamin Petersonf650e462010-05-06 23:03:05 +0000609 :func:`fork` and :func:`execv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000610
611 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
612 automatically translated into a corresponding call to :func:`unsetenv`; however,
613 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
614 preferable to delete items of ``os.environ``.
615
Benjamin Petersonf650e462010-05-06 23:03:05 +0000616 Availability: most flavors of Unix, Windows.
617
Georg Brandl116aa622007-08-15 14:28:22 +0000618
619.. _os-newstreams:
620
621File Object Creation
622--------------------
623
Georg Brandla570e982012-06-24 13:26:22 +0200624This function creates new :term:`file objects <file object>`. (See also
Georg Brandlb2462e22012-06-24 13:24:56 +0200625:func:`~os.open` for opening file descriptors.)
Georg Brandl116aa622007-08-15 14:28:22 +0000626
627
Petri Lehtinen1a01ebc2012-05-24 21:44:07 +0300628.. function:: fdopen(fd, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000629
Georg Brandlb2462e22012-06-24 13:24:56 +0200630 Return an open file object connected to the file descriptor *fd*. This is an
631 alias of the :func:`open` built-in function and accepts the same arguments.
632 The only difference is that the first argument of :func:`fdopen` must always
633 be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000634
Georg Brandl116aa622007-08-15 14:28:22 +0000635
Georg Brandl116aa622007-08-15 14:28:22 +0000636.. _os-fd-ops:
637
638File Descriptor Operations
639--------------------------
640
641These functions operate on I/O streams referenced using file descriptors.
642
643File descriptors are small integers corresponding to a file that has been opened
644by the current process. For example, standard input is usually file descriptor
6450, standard output is 1, and standard error is 2. Further files opened by a
646process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
647is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
648by file descriptors.
649
Serhiy Storchakadab83542013-10-13 20:12:43 +0300650The :meth:`~io.IOBase.fileno` method can be used to obtain the file descriptor
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000651associated with a :term:`file object` when required. Note that using the file
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000652descriptor directly will bypass the file object methods, ignoring aspects such
653as internal buffering of data.
Georg Brandl116aa622007-08-15 14:28:22 +0000654
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000655
Georg Brandl116aa622007-08-15 14:28:22 +0000656.. function:: close(fd)
657
Benjamin Petersonf650e462010-05-06 23:03:05 +0000658 Close file descriptor *fd*.
659
660 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000661
662 .. note::
663
664 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000665 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
Georg Brandl116aa622007-08-15 14:28:22 +0000666 object" returned by the built-in function :func:`open` or by :func:`popen` or
Serhiy Storchakadab83542013-10-13 20:12:43 +0300667 :func:`fdopen`, use its :meth:`~io.IOBase.close` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000668
669
Christian Heimesfdab48e2008-01-20 09:06:41 +0000670.. function:: closerange(fd_low, fd_high)
671
672 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
Georg Brandlb1a1ac02012-06-24 11:54:07 +0200673 ignoring errors. Equivalent to (but much faster than)::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000674
Georg Brandlc9a5a0e2009-09-01 07:34:27 +0000675 for fd in range(fd_low, fd_high):
Christian Heimesfdab48e2008-01-20 09:06:41 +0000676 try:
677 os.close(fd)
678 except OSError:
679 pass
680
Benjamin Petersonf650e462010-05-06 23:03:05 +0000681 Availability: Unix, Windows.
682
Christian Heimesfdab48e2008-01-20 09:06:41 +0000683
Georg Brandl81f11302007-12-21 08:45:42 +0000684.. function:: device_encoding(fd)
685
686 Return a string describing the encoding of the device associated with *fd*
687 if it is connected to a terminal; else return :const:`None`.
688
689
Georg Brandl116aa622007-08-15 14:28:22 +0000690.. function:: dup(fd)
691
Victor Stinnerdaf45552013-08-28 00:53:59 +0200692 Return a duplicate of file descriptor *fd*. The new file descriptor is
693 :ref:`non-inheritable <fd_inheritance>`.
694
695 On Windows, when duplicating a standard stream (0: stdin, 1: stdout,
696 2: stderr), the new file descriptor is :ref:`inheritable
697 <fd_inheritance>`.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000698
699 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000700
Victor Stinnerdaf45552013-08-28 00:53:59 +0200701 .. versionchanged:: 3.4
702 The new file descriptor is now non-inheritable.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Victor Stinnerdaf45552013-08-28 00:53:59 +0200704
705.. function:: dup2(fd, fd2, inheritable=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000706
707 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
Victor Stinnerdaf45552013-08-28 00:53:59 +0200708 The file descriptor *fd2* is :ref:`inheritable <fd_inheritance>` by default,
709 or non-inheritable if *inheritable* is ``False``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000710
Georg Brandlc575c902008-09-13 17:46:05 +0000711 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000712
Victor Stinnerdaf45552013-08-28 00:53:59 +0200713 .. versionchanged:: 3.4
714 Add the optional *inheritable* parameter.
715
Georg Brandl116aa622007-08-15 14:28:22 +0000716
Christian Heimes4e30a842007-11-30 22:12:06 +0000717.. function:: fchmod(fd, mode)
718
Georg Brandlb9df00c2012-06-24 12:38:14 +0200719 Change the mode of the file given by *fd* to the numeric *mode*. See the
Georg Brandl4d399a42012-06-25 07:40:32 +0200720 docs for :func:`chmod` for possible values of *mode*. As of Python 3.3, this
Georg Brandlb9df00c2012-06-24 12:38:14 +0200721 is equivalent to ``os.chmod(fd, mode)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000722
723 Availability: Unix.
Christian Heimes4e30a842007-11-30 22:12:06 +0000724
725
726.. function:: fchown(fd, uid, gid)
727
728 Change the owner and group id of the file given by *fd* to the numeric *uid*
Georg Brandlb9df00c2012-06-24 12:38:14 +0200729 and *gid*. To leave one of the ids unchanged, set it to -1. See
Georg Brandl4d399a42012-06-25 07:40:32 +0200730 :func:`chown`. As of Python 3.3, this is equivalent to ``os.chown(fd, uid,
Georg Brandlb9df00c2012-06-24 12:38:14 +0200731 gid)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000732
Christian Heimes4e30a842007-11-30 22:12:06 +0000733 Availability: Unix.
734
735
Georg Brandl116aa622007-08-15 14:28:22 +0000736.. function:: fdatasync(fd)
737
738 Force write of file with filedescriptor *fd* to disk. Does not force update of
Benjamin Petersonf650e462010-05-06 23:03:05 +0000739 metadata.
740
741 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000743 .. note::
744 This function is not available on MacOS.
745
Georg Brandl116aa622007-08-15 14:28:22 +0000746
747.. function:: fpathconf(fd, name)
748
749 Return system configuration information relevant to an open file. *name*
750 specifies the configuration value to retrieve; it may be a string which is the
751 name of a defined system value; these names are specified in a number of
752 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
753 additional names as well. The names known to the host operating system are
754 given in the ``pathconf_names`` dictionary. For configuration variables not
755 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +0000756
757 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
758 specific value for *name* is not supported by the host system, even if it is
759 included in ``pathconf_names``, an :exc:`OSError` is raised with
760 :const:`errno.EINVAL` for the error number.
761
Georg Brandl4d399a42012-06-25 07:40:32 +0200762 As of Python 3.3, this is equivalent to ``os.pathconf(fd, name)``.
Georg Brandl306336b2012-06-24 12:55:33 +0200763
Senthil Kumaran2a97cee2013-09-19 00:08:56 -0700764 Availability: Unix.
765
Georg Brandl116aa622007-08-15 14:28:22 +0000766
Victor Stinner4195b5c2012-02-08 23:03:19 +0100767.. function:: fstat(fd)
Georg Brandl116aa622007-08-15 14:28:22 +0000768
Victor Stinner6d4f4fe2014-07-24 12:42:16 +0200769 Get the status of the file descriptor *fd*. Return a :class:`stat_result`
770 object.
771
772 As of Python 3.3, this is equivalent to ``os.stat(fd)``.
773
774 .. seealso::
775
Berker Peksag2034caa2015-04-27 13:53:28 +0300776 The :func:`.stat` function.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000777
778 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000779
Georg Brandlb1a1ac02012-06-24 11:54:07 +0200780
Georg Brandl116aa622007-08-15 14:28:22 +0000781.. function:: fstatvfs(fd)
782
Georg Brandlb9df00c2012-06-24 12:38:14 +0200783 Return information about the filesystem containing the file associated with
Georg Brandl4d399a42012-06-25 07:40:32 +0200784 file descriptor *fd*, like :func:`statvfs`. As of Python 3.3, this is
Georg Brandlb9df00c2012-06-24 12:38:14 +0200785 equivalent to ``os.statvfs(fd)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000786
787 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000788
789
790.. function:: fsync(fd)
791
792 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
Georg Brandl60203b42010-10-06 10:11:56 +0000793 native :c:func:`fsync` function; on Windows, the MS :c:func:`_commit` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000794
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000795 If you're starting with a buffered Python :term:`file object` *f*, first do
796 ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal
797 buffers associated with *f* are written to disk.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000798
Georg Brandl8a5555f2012-06-24 13:29:09 +0200799 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000800
801
802.. function:: ftruncate(fd, length)
803
Georg Brandl306336b2012-06-24 12:55:33 +0200804 Truncate the file corresponding to file descriptor *fd*, so that it is at
Georg Brandl4d399a42012-06-25 07:40:32 +0200805 most *length* bytes in size. As of Python 3.3, this is equivalent to
Georg Brandl306336b2012-06-24 12:55:33 +0200806 ``os.truncate(fd, length)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000807
Steve Dowerfe0a41a2015-03-20 19:50:46 -0700808 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000809
Steve Dowerfe0a41a2015-03-20 19:50:46 -0700810 .. versionchanged:: 3.5
811 Added support for Windows
Georg Brandl116aa622007-08-15 14:28:22 +0000812
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200813.. function:: get_blocking(fd)
814
815 Get the blocking mode of the file descriptor: ``False`` if the
816 :data:`O_NONBLOCK` flag is set, ``True`` if the flag is cleared.
817
818 See also :func:`set_blocking` and :meth:`socket.socket.setblocking`.
819
820 Availability: Unix.
821
822 .. versionadded:: 3.5
823
Georg Brandl116aa622007-08-15 14:28:22 +0000824.. function:: isatty(fd)
825
826 Return ``True`` if the file descriptor *fd* is open and connected to a
Benjamin Petersonf650e462010-05-06 23:03:05 +0000827 tty(-like) device, else ``False``.
828
Georg Brandl116aa622007-08-15 14:28:22 +0000829
Ross Lagerwall7807c352011-03-17 20:20:30 +0200830.. function:: lockf(fd, cmd, len)
831
832 Apply, test or remove a POSIX lock on an open file descriptor.
833 *fd* is an open file descriptor.
834 *cmd* specifies the command to use - one of :data:`F_LOCK`, :data:`F_TLOCK`,
835 :data:`F_ULOCK` or :data:`F_TEST`.
836 *len* specifies the section of the file to lock.
837
838 Availability: Unix.
839
840 .. versionadded:: 3.3
841
842
843.. data:: F_LOCK
844 F_TLOCK
845 F_ULOCK
846 F_TEST
847
848 Flags that specify what action :func:`lockf` will take.
849
850 Availability: Unix.
851
852 .. versionadded:: 3.3
853
Georg Brandlf62445a2012-06-24 13:31:20 +0200854
Georg Brandl116aa622007-08-15 14:28:22 +0000855.. function:: lseek(fd, pos, how)
856
Christian Heimesfaf2f632008-01-06 16:59:19 +0000857 Set the current position of file descriptor *fd* to position *pos*, modified
858 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
859 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
Serhiy Storchakadab83542013-10-13 20:12:43 +0300860 current position; :const:`SEEK_END` or ``2`` to set it relative to the end of
Victor Stinnere83f8992011-12-17 23:15:09 +0100861 the file. Return the new cursor position in bytes, starting from the beginning.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000862
863 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000864
865
Georg Brandl8569e582010-05-19 20:57:08 +0000866.. data:: SEEK_SET
867 SEEK_CUR
868 SEEK_END
869
870 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
Georg Brandl8a5555f2012-06-24 13:29:09 +0200871 respectively.
872
873 Availability: Unix, Windows.
Georg Brandl8569e582010-05-19 20:57:08 +0000874
Jesus Cea94363612012-06-22 18:32:07 +0200875 .. versionadded:: 3.3
876 Some operating systems could support additional values, like
877 :data:`os.SEEK_HOLE` or :data:`os.SEEK_DATA`.
878
Georg Brandl8569e582010-05-19 20:57:08 +0000879
Larry Hastings9cf065c2012-06-22 16:30:09 -0700880.. function:: open(file, flags, mode=0o777, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000881
Georg Brandlf4a41232008-05-26 17:55:52 +0000882 Open the file *file* and set various flags according to *flags* and possibly
Larry Hastings9cf065c2012-06-22 16:30:09 -0700883 its mode according to *mode*. When computing *mode*, the current umask value
884 is first masked out. Return the file descriptor for the newly opened file.
Victor Stinnerdaf45552013-08-28 00:53:59 +0200885 The new file descriptor is :ref:`non-inheritable <fd_inheritance>`.
Georg Brandl116aa622007-08-15 14:28:22 +0000886
887 For a description of the flag and mode values, see the C run-time documentation;
888 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
Andrew Kuchling4921a082013-06-21 11:49:57 -0400889 the :mod:`os` module. In particular, on Windows adding
Georg Brandl8569e582010-05-19 20:57:08 +0000890 :const:`O_BINARY` is needed to open files in binary mode.
Georg Brandl116aa622007-08-15 14:28:22 +0000891
Georg Brandl50c40002012-06-24 11:45:20 +0200892 This function can support :ref:`paths relative to directory descriptors
Andrew Kuchling4921a082013-06-21 11:49:57 -0400893 <dir_fd>` with the *dir_fd* parameter.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700894
Benjamin Petersonf650e462010-05-06 23:03:05 +0000895 Availability: Unix, Windows.
896
Victor Stinnerdaf45552013-08-28 00:53:59 +0200897 .. versionchanged:: 3.4
898 The new file descriptor is now non-inheritable.
899
Georg Brandl116aa622007-08-15 14:28:22 +0000900 .. note::
901
Georg Brandl502d9a52009-07-26 15:02:41 +0000902 This function is intended for low-level I/O. For normal usage, use the
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000903 built-in function :func:`open`, which returns a :term:`file object` with
Jeroen Ruigrok van der Werven9c558bcf2010-07-13 14:47:01 +0000904 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000905 wrap a file descriptor in a file object, use :func:`fdopen`.
Georg Brandl116aa622007-08-15 14:28:22 +0000906
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000907 .. versionadded:: 3.3
Larry Hastings9cf065c2012-06-22 16:30:09 -0700908 The *dir_fd* argument.
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000909
Victor Stinnera766ddf2015-03-26 23:50:57 +0100910 .. versionchanged:: 3.5
Victor Stinner708d9ba2015-04-02 11:49:42 +0200911 If the system call is interrupted and the signal handler does not raise an
Victor Stinnera766ddf2015-03-26 23:50:57 +0100912 exception, the function now retries the system call instead of raising an
913 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
914
Andrew Kuchling4921a082013-06-21 11:49:57 -0400915The following constants are options for the *flags* parameter to the
916:func:`~os.open` function. They can be combined using the bitwise OR operator
917``|``. Some of them are not available on all platforms. For descriptions of
918their availability and use, consult the :manpage:`open(2)` manual page on Unix
919or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
920
921
922.. data:: O_RDONLY
923 O_WRONLY
924 O_RDWR
925 O_APPEND
926 O_CREAT
927 O_EXCL
928 O_TRUNC
929
930 These constants are available on Unix and Windows.
931
932
933.. data:: O_DSYNC
934 O_RSYNC
935 O_SYNC
936 O_NDELAY
937 O_NONBLOCK
938 O_NOCTTY
939 O_SHLOCK
940 O_EXLOCK
941 O_CLOEXEC
942
943 These constants are only available on Unix.
944
945 .. versionchanged:: 3.3
946 Add :data:`O_CLOEXEC` constant.
947
948.. data:: O_BINARY
949 O_NOINHERIT
950 O_SHORT_LIVED
951 O_TEMPORARY
952 O_RANDOM
953 O_SEQUENTIAL
954 O_TEXT
955
956 These constants are only available on Windows.
957
958
959.. data:: O_ASYNC
960 O_DIRECT
961 O_DIRECTORY
962 O_NOFOLLOW
963 O_NOATIME
964 O_PATH
Christian Heimes177b3f92013-08-16 14:35:09 +0200965 O_TMPFILE
Andrew Kuchling4921a082013-06-21 11:49:57 -0400966
967 These constants are GNU extensions and not present if they are not defined by
968 the C library.
969
Christian Heimesd88f7352013-08-16 14:37:50 +0200970 .. versionchanged:: 3.4
Larry Hastings3732ed22014-03-15 21:13:56 -0700971 Add :data:`O_PATH` on systems that support it.
972 Add :data:`O_TMPFILE`, only available on Linux Kernel 3.11
973 or newer.
Christian Heimesd88f7352013-08-16 14:37:50 +0200974
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000975
Georg Brandl116aa622007-08-15 14:28:22 +0000976.. function:: openpty()
977
978 .. index:: module: pty
979
Victor Stinnerdaf45552013-08-28 00:53:59 +0200980 Open a new pseudo-terminal pair. Return a pair of file descriptors
981 ``(master, slave)`` for the pty and the tty, respectively. The new file
982 descriptors are :ref:`non-inheritable <fd_inheritance>`. For a (slightly) more
983 portable approach, use the :mod:`pty` module.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000984
985 Availability: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000986
Victor Stinnerdaf45552013-08-28 00:53:59 +0200987 .. versionchanged:: 3.4
988 The new file descriptors are now non-inheritable.
989
Georg Brandl116aa622007-08-15 14:28:22 +0000990
991.. function:: pipe()
992
Victor Stinnerdaf45552013-08-28 00:53:59 +0200993 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for
Victor Stinner05f31bf2013-11-06 01:48:45 +0100994 reading and writing, respectively. The new file descriptor is
Victor Stinnerdaf45552013-08-28 00:53:59 +0200995 :ref:`non-inheritable <fd_inheritance>`.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000996
997 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000998
Victor Stinnerdaf45552013-08-28 00:53:59 +0200999 .. versionchanged:: 3.4
1000 The new file descriptors are now non-inheritable.
1001
Georg Brandl116aa622007-08-15 14:28:22 +00001002
Charles-François Natali368f34b2011-06-06 19:49:47 +02001003.. function:: pipe2(flags)
Charles-François Natalidaafdd52011-05-29 20:07:40 +02001004
1005 Create a pipe with *flags* set atomically.
Charles-François Natali368f34b2011-06-06 19:49:47 +02001006 *flags* can be constructed by ORing together one or more of these values:
1007 :data:`O_NONBLOCK`, :data:`O_CLOEXEC`.
Charles-François Natalidaafdd52011-05-29 20:07:40 +02001008 Return a pair of file descriptors ``(r, w)`` usable for reading and writing,
1009 respectively.
1010
1011 Availability: some flavors of Unix.
1012
1013 .. versionadded:: 3.3
1014
1015
Ross Lagerwall7807c352011-03-17 20:20:30 +02001016.. function:: posix_fallocate(fd, offset, len)
1017
1018 Ensures that enough disk space is allocated for the file specified by *fd*
1019 starting from *offset* and continuing for *len* bytes.
1020
1021 Availability: Unix.
1022
1023 .. versionadded:: 3.3
1024
1025
1026.. function:: posix_fadvise(fd, offset, len, advice)
1027
1028 Announces an intention to access data in a specific pattern thus allowing
1029 the kernel to make optimizations.
1030 The advice applies to the region of the file specified by *fd* starting at
1031 *offset* and continuing for *len* bytes.
1032 *advice* is one of :data:`POSIX_FADV_NORMAL`, :data:`POSIX_FADV_SEQUENTIAL`,
1033 :data:`POSIX_FADV_RANDOM`, :data:`POSIX_FADV_NOREUSE`,
1034 :data:`POSIX_FADV_WILLNEED` or :data:`POSIX_FADV_DONTNEED`.
1035
1036 Availability: Unix.
1037
1038 .. versionadded:: 3.3
1039
1040
1041.. data:: POSIX_FADV_NORMAL
1042 POSIX_FADV_SEQUENTIAL
1043 POSIX_FADV_RANDOM
1044 POSIX_FADV_NOREUSE
1045 POSIX_FADV_WILLNEED
1046 POSIX_FADV_DONTNEED
1047
1048 Flags that can be used in *advice* in :func:`posix_fadvise` that specify
1049 the access pattern that is likely to be used.
1050
1051 Availability: Unix.
1052
1053 .. versionadded:: 3.3
1054
1055
1056.. function:: pread(fd, buffersize, offset)
1057
1058 Read from a file descriptor, *fd*, at a position of *offset*. It will read up
1059 to *buffersize* number of bytes. The file offset remains unchanged.
1060
1061 Availability: Unix.
1062
1063 .. versionadded:: 3.3
1064
1065
Jesus Cea67503c52014-10-20 16:18:24 +02001066.. function:: pwrite(fd, str, offset)
Ross Lagerwall7807c352011-03-17 20:20:30 +02001067
Jesus Cea67503c52014-10-20 16:18:24 +02001068 Write *bytestring* to a file descriptor, *fd*, from *offset*,
1069 leaving the file offset unchanged.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001070
1071 Availability: Unix.
1072
1073 .. versionadded:: 3.3
1074
1075
Georg Brandl116aa622007-08-15 14:28:22 +00001076.. function:: read(fd, n)
1077
Georg Brandlb90be692009-07-29 16:14:16 +00001078 Read at most *n* bytes from file descriptor *fd*. Return a bytestring containing the
Georg Brandl116aa622007-08-15 14:28:22 +00001079 bytes read. If the end of the file referred to by *fd* has been reached, an
Benjamin Petersonf650e462010-05-06 23:03:05 +00001080 empty bytes object is returned.
1081
1082 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001083
1084 .. note::
1085
1086 This function is intended for low-level I/O and must be applied to a file
Georg Brandlb2462e22012-06-24 13:24:56 +02001087 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a
1088 "file object" returned by the built-in function :func:`open` or by
1089 :func:`popen` or :func:`fdopen`, or :data:`sys.stdin`, use its
1090 :meth:`~file.read` or :meth:`~file.readline` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00001091
Victor Stinnera766ddf2015-03-26 23:50:57 +01001092 .. versionchanged:: 3.5
Victor Stinner708d9ba2015-04-02 11:49:42 +02001093 If the system call is interrupted and the signal handler does not raise an
Victor Stinnera766ddf2015-03-26 23:50:57 +01001094 exception, the function now retries the system call instead of raising an
1095 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1096
Georg Brandl116aa622007-08-15 14:28:22 +00001097
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001098.. function:: sendfile(out, in, offset, nbytes)
1099 sendfile(out, in, offset, nbytes, headers=None, trailers=None, flags=0)
1100
1101 Copy *nbytes* bytes from file descriptor *in* to file descriptor *out*
1102 starting at *offset*.
1103 Return the number of bytes sent. When EOF is reached return 0.
1104
1105 The first function notation is supported by all platforms that define
1106 :func:`sendfile`.
1107
1108 On Linux, if *offset* is given as ``None``, the bytes are read from the
1109 current position of *in* and the position of *in* is updated.
1110
1111 The second case may be used on Mac OS X and FreeBSD where *headers* and
1112 *trailers* are arbitrary sequences of buffers that are written before and
1113 after the data from *in* is written. It returns the same as the first case.
1114
1115 On Mac OS X and FreeBSD, a value of 0 for *nbytes* specifies to send until
1116 the end of *in* is reached.
1117
Charles-Francois Natalia771a1b2013-05-01 15:12:20 +02001118 All platforms support sockets as *out* file descriptor, and some platforms
1119 allow other types (e.g. regular file, pipe) as well.
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001120
Giampaolo Rodola'409569b2014-04-24 18:09:21 +02001121 Cross-platform applications should not use *headers*, *trailers* and *flags*
1122 arguments.
1123
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001124 Availability: Unix.
1125
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02001126 .. note::
1127
Benjamin Peterson0ce95372014-06-15 18:30:27 -07001128 For a higher-level wrapper of :func:`sendfile`, see
1129 :mod:`socket.socket.sendfile`.
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02001130
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001131 .. versionadded:: 3.3
1132
1133
Victor Stinner1db9e7b2014-07-29 22:32:47 +02001134.. function:: set_blocking(fd, blocking)
1135
1136 Set the blocking mode of the specified file descriptor. Set the
1137 :data:`O_NONBLOCK` flag if blocking is ``False``, clear the flag otherwise.
1138
1139 See also :func:`get_blocking` and :meth:`socket.socket.setblocking`.
1140
1141 Availability: Unix.
1142
1143 .. versionadded:: 3.5
1144
1145
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001146.. data:: SF_NODISKIO
1147 SF_MNOWAIT
1148 SF_SYNC
1149
1150 Parameters to the :func:`sendfile` function, if the implementation supports
1151 them.
1152
1153 Availability: Unix.
1154
1155 .. versionadded:: 3.3
1156
1157
Ross Lagerwall7807c352011-03-17 20:20:30 +02001158.. function:: readv(fd, buffers)
1159
Benjamin Petersone83ed432014-01-18 22:54:59 -05001160 Read from a file descriptor *fd* into a number of mutable :term:`bytes-like
1161 objects <bytes-like object>` *buffers*. :func:`~os.readv` will transfer data
1162 into each buffer until it is full and then move on to the next buffer in the
1163 sequence to hold the rest of the data. :func:`~os.readv` returns the total
1164 number of bytes read (which may be less than the total capacity of all the
1165 objects).
Ross Lagerwall7807c352011-03-17 20:20:30 +02001166
1167 Availability: Unix.
1168
1169 .. versionadded:: 3.3
1170
1171
Georg Brandl116aa622007-08-15 14:28:22 +00001172.. function:: tcgetpgrp(fd)
1173
1174 Return the process group associated with the terminal given by *fd* (an open
Benjamin Petersonf650e462010-05-06 23:03:05 +00001175 file descriptor as returned by :func:`os.open`).
1176
1177 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001178
1179
1180.. function:: tcsetpgrp(fd, pg)
1181
1182 Set the process group associated with the terminal given by *fd* (an open file
Benjamin Petersonf650e462010-05-06 23:03:05 +00001183 descriptor as returned by :func:`os.open`) to *pg*.
1184
1185 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001186
1187
1188.. function:: ttyname(fd)
1189
1190 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +00001191 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Benjamin Petersonf650e462010-05-06 23:03:05 +00001192 exception is raised.
1193
1194 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001195
1196
1197.. function:: write(fd, str)
1198
Georg Brandlb90be692009-07-29 16:14:16 +00001199 Write the bytestring in *str* to file descriptor *fd*. Return the number of
Benjamin Petersonf650e462010-05-06 23:03:05 +00001200 bytes actually written.
1201
1202 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001203
1204 .. note::
1205
1206 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001207 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
Georg Brandl116aa622007-08-15 14:28:22 +00001208 object" returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001209 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
1210 :meth:`~file.write` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001211
Victor Stinnera766ddf2015-03-26 23:50:57 +01001212 .. versionchanged:: 3.5
Victor Stinner708d9ba2015-04-02 11:49:42 +02001213 If the system call is interrupted and the signal handler does not raise an
Victor Stinnera766ddf2015-03-26 23:50:57 +01001214 exception, the function now retries the system call instead of raising an
1215 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1216
Georg Brandl8569e582010-05-19 20:57:08 +00001217
Ross Lagerwall7807c352011-03-17 20:20:30 +02001218.. function:: writev(fd, buffers)
1219
Benjamin Petersone83ed432014-01-18 22:54:59 -05001220 Write the contents of *buffers* to file descriptor *fd*. *buffers* must be a
1221 sequence of :term:`bytes-like objects <bytes-like object>`.
1222 :func:`~os.writev` writes the contents of each object to the file descriptor
1223 and returns the total number of bytes written.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001224
1225 Availability: Unix.
1226
1227 .. versionadded:: 3.3
1228
1229
Antoine Pitroubcf2b592012-02-08 23:28:36 +01001230.. _terminal-size:
1231
1232Querying the size of a terminal
1233~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1234
1235.. versionadded:: 3.3
1236
1237.. function:: get_terminal_size(fd=STDOUT_FILENO)
1238
1239 Return the size of the terminal window as ``(columns, lines)``,
1240 tuple of type :class:`terminal_size`.
1241
1242 The optional argument ``fd`` (default ``STDOUT_FILENO``, or standard
1243 output) specifies which file descriptor should be queried.
1244
1245 If the file descriptor is not connected to a terminal, an :exc:`OSError`
Andrew Svetlov5b898402012-12-18 21:26:36 +02001246 is raised.
Antoine Pitroubcf2b592012-02-08 23:28:36 +01001247
1248 :func:`shutil.get_terminal_size` is the high-level function which
1249 should normally be used, ``os.get_terminal_size`` is the low-level
1250 implementation.
1251
1252 Availability: Unix, Windows.
1253
Georg Brandl6cff9ff2012-06-24 14:05:40 +02001254.. class:: terminal_size
Antoine Pitroubcf2b592012-02-08 23:28:36 +01001255
Georg Brandl6cff9ff2012-06-24 14:05:40 +02001256 A subclass of tuple, holding ``(columns, lines)`` of the terminal window size.
Antoine Pitroubcf2b592012-02-08 23:28:36 +01001257
1258 .. attribute:: columns
1259
1260 Width of the terminal window in characters.
1261
1262 .. attribute:: lines
1263
1264 Height of the terminal window in characters.
1265
1266
Victor Stinnerdaf45552013-08-28 00:53:59 +02001267.. _fd_inheritance:
1268
1269Inheritance of File Descriptors
1270~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1271
Georg Brandl5642ff92013-09-15 10:37:57 +02001272.. versionadded:: 3.4
1273
1274A file descriptor has an "inheritable" flag which indicates if the file descriptor
1275can be inherited by child processes. Since Python 3.4, file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001276created by Python are non-inheritable by default.
1277
1278On UNIX, non-inheritable file descriptors are closed in child processes at the
1279execution of a new program, other file descriptors are inherited.
1280
1281On Windows, non-inheritable handles and file descriptors are closed in child
Georg Brandl5642ff92013-09-15 10:37:57 +02001282processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout
Serhiy Storchaka690a6a92013-10-13 20:13:37 +03001283and stderr), which are always inherited. Using :func:`spawn\* <spawnl>` functions,
Victor Stinnerdaf45552013-08-28 00:53:59 +02001284all inheritable handles and all inheritable file descriptors are inherited.
1285Using the :mod:`subprocess` module, all file descriptors except standard
Georg Brandl5642ff92013-09-15 10:37:57 +02001286streams are closed, and inheritable handles are only inherited if the
1287*close_fds* parameter is ``False``.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001288
1289.. function:: get_inheritable(fd)
1290
Georg Brandl5642ff92013-09-15 10:37:57 +02001291 Get the "inheritable" flag of the specified file descriptor (a boolean).
Victor Stinnerdaf45552013-08-28 00:53:59 +02001292
1293.. function:: set_inheritable(fd, inheritable)
1294
Georg Brandl5642ff92013-09-15 10:37:57 +02001295 Set the "inheritable" flag of the specified file descriptor.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001296
1297.. function:: get_handle_inheritable(handle)
1298
Georg Brandl5642ff92013-09-15 10:37:57 +02001299 Get the "inheritable" flag of the specified handle (a boolean).
Victor Stinnerdaf45552013-08-28 00:53:59 +02001300
1301 Availability: Windows.
1302
1303.. function:: set_handle_inheritable(handle, inheritable)
1304
Georg Brandl5642ff92013-09-15 10:37:57 +02001305 Set the "inheritable" flag of the specified handle.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001306
1307 Availability: Windows.
1308
1309
Georg Brandl116aa622007-08-15 14:28:22 +00001310.. _os-file-dir:
1311
1312Files and Directories
1313---------------------
1314
Georg Brandl50c40002012-06-24 11:45:20 +02001315On some Unix platforms, many of these functions support one or more of these
1316features:
1317
1318.. _path_fd:
1319
Larry Hastings77892dc2012-06-25 03:27:33 -07001320* **specifying a file descriptor:**
1321 For some functions, the *path* argument can be not only a string giving a path
Georg Brandl50c40002012-06-24 11:45:20 +02001322 name, but also a file descriptor. The function will then operate on the file
Georg Brandlaceaf902012-06-25 08:33:56 +02001323 referred to by the descriptor. (For POSIX systems, Python will call the
1324 ``f...`` version of the function.)
Georg Brandl50c40002012-06-24 11:45:20 +02001325
1326 You can check whether or not *path* can be specified as a file descriptor on
1327 your platform using :data:`os.supports_fd`. If it is unavailable, using it
1328 will raise a :exc:`NotImplementedError`.
1329
1330 If the function also supports *dir_fd* or *follow_symlinks* arguments, it is
1331 an error to specify one of those when supplying *path* as a file descriptor.
1332
1333.. _dir_fd:
1334
Larry Hastings77892dc2012-06-25 03:27:33 -07001335* **paths relative to directory descriptors:** If *dir_fd* is not ``None``, it
Georg Brandl50c40002012-06-24 11:45:20 +02001336 should be a file descriptor referring to a directory, and the path to operate
1337 on should be relative; path will then be relative to that directory. If the
Georg Brandlaceaf902012-06-25 08:33:56 +02001338 path is absolute, *dir_fd* is ignored. (For POSIX systems, Python will call
Larry Hastings77892dc2012-06-25 03:27:33 -07001339 the ``...at`` or ``f...at`` version of the function.)
Georg Brandl50c40002012-06-24 11:45:20 +02001340
1341 You can check whether or not *dir_fd* is supported on your platform using
1342 :data:`os.supports_dir_fd`. If it is unavailable, using it will raise a
1343 :exc:`NotImplementedError`.
1344
1345.. _follow_symlinks:
1346
Larry Hastings77892dc2012-06-25 03:27:33 -07001347* **not following symlinks:** If *follow_symlinks* is
Georg Brandl50c40002012-06-24 11:45:20 +02001348 ``False``, and the last element of the path to operate on is a symbolic link,
1349 the function will operate on the symbolic link itself instead of the file the
Georg Brandlaceaf902012-06-25 08:33:56 +02001350 link points to. (For POSIX systems, Python will call the ``l...`` version of
Georg Brandl50c40002012-06-24 11:45:20 +02001351 the function.)
1352
1353 You can check whether or not *follow_symlinks* is supported on your platform
1354 using :data:`os.supports_follow_symlinks`. If it is unavailable, using it
1355 will raise a :exc:`NotImplementedError`.
1356
1357
1358
Larry Hastings9cf065c2012-06-22 16:30:09 -07001359.. function:: access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001360
1361 Use the real uid/gid to test for access to *path*. Note that most operations
1362 will use the effective uid/gid, therefore this routine can be used in a
1363 suid/sgid environment to test if the invoking user has the specified access to
1364 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
1365 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
1366 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
1367 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
Benjamin Petersonf650e462010-05-06 23:03:05 +00001368 information.
1369
Georg Brandl50c40002012-06-24 11:45:20 +02001370 This function can support specifying :ref:`paths relative to directory
1371 descriptors <dir_fd>` and :ref:`not following symlinks <follow_symlinks>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001372
1373 If *effective_ids* is ``True``, :func:`access` will perform its access
1374 checks using the effective uid/gid instead of the real uid/gid.
1375 *effective_ids* may not be supported on your platform; you can check whether
1376 or not it is available using :data:`os.supports_effective_ids`. If it is
1377 unavailable, using it will raise a :exc:`NotImplementedError`.
1378
Benjamin Petersonf650e462010-05-06 23:03:05 +00001379 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001380
1381 .. note::
1382
Georg Brandl502d9a52009-07-26 15:02:41 +00001383 Using :func:`access` to check if a user is authorized to e.g. open a file
1384 before actually doing so using :func:`open` creates a security hole,
1385 because the user might exploit the short time interval between checking
Benjamin Peterson249b5082011-05-20 11:41:13 -05001386 and opening the file to manipulate it. It's preferable to use :term:`EAFP`
1387 techniques. For example::
1388
1389 if os.access("myfile", os.R_OK):
1390 with open("myfile") as fp:
1391 return fp.read()
1392 return "some default data"
1393
1394 is better written as::
1395
1396 try:
1397 fp = open("myfile")
Antoine Pitrou62ab10a02011-10-12 20:10:51 +02001398 except PermissionError:
1399 return "some default data"
Benjamin Peterson249b5082011-05-20 11:41:13 -05001400 else:
1401 with fp:
1402 return fp.read()
Georg Brandl116aa622007-08-15 14:28:22 +00001403
1404 .. note::
1405
1406 I/O operations may fail even when :func:`access` indicates that they would
1407 succeed, particularly for operations on network filesystems which may have
1408 permissions semantics beyond the usual POSIX permission-bit model.
1409
Larry Hastings9cf065c2012-06-22 16:30:09 -07001410 .. versionchanged:: 3.3
1411 Added the *dir_fd*, *effective_ids*, and *follow_symlinks* parameters.
1412
Georg Brandl116aa622007-08-15 14:28:22 +00001413
1414.. data:: F_OK
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001415 R_OK
1416 W_OK
1417 X_OK
Georg Brandl116aa622007-08-15 14:28:22 +00001418
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001419 Values to pass as the *mode* parameter of :func:`access` to test the
1420 existence, readability, writability and executability of *path*,
1421 respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001422
1423
1424.. function:: chdir(path)
1425
1426 .. index:: single: directory; changing
1427
Benjamin Petersonf650e462010-05-06 23:03:05 +00001428 Change the current working directory to *path*.
1429
Larry Hastings77892dc2012-06-25 03:27:33 -07001430 This function can support :ref:`specifying a file descriptor <path_fd>`. The
Georg Brandl50c40002012-06-24 11:45:20 +02001431 descriptor must refer to an opened directory, not an open file.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001432
Benjamin Petersonf650e462010-05-06 23:03:05 +00001433 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001434
Larry Hastings9cf065c2012-06-22 16:30:09 -07001435 .. versionadded:: 3.3
1436 Added support for specifying *path* as a file descriptor
Georg Brandl50c40002012-06-24 11:45:20 +02001437 on some platforms.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001438
Georg Brandl116aa622007-08-15 14:28:22 +00001439
Larry Hastings9cf065c2012-06-22 16:30:09 -07001440.. function:: chflags(path, flags, *, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001441
1442 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
1443 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
1444
R David Murray30178062011-03-10 17:18:33 -05001445 * :data:`stat.UF_NODUMP`
1446 * :data:`stat.UF_IMMUTABLE`
1447 * :data:`stat.UF_APPEND`
1448 * :data:`stat.UF_OPAQUE`
1449 * :data:`stat.UF_NOUNLINK`
Ned Deily3eb67d52011-06-28 00:00:28 -07001450 * :data:`stat.UF_COMPRESSED`
1451 * :data:`stat.UF_HIDDEN`
R David Murray30178062011-03-10 17:18:33 -05001452 * :data:`stat.SF_ARCHIVED`
1453 * :data:`stat.SF_IMMUTABLE`
1454 * :data:`stat.SF_APPEND`
1455 * :data:`stat.SF_NOUNLINK`
1456 * :data:`stat.SF_SNAPSHOT`
Georg Brandl116aa622007-08-15 14:28:22 +00001457
Georg Brandl50c40002012-06-24 11:45:20 +02001458 This function can support :ref:`not following symlinks <follow_symlinks>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001459
Georg Brandlc575c902008-09-13 17:46:05 +00001460 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001461
Larry Hastings9cf065c2012-06-22 16:30:09 -07001462 .. versionadded:: 3.3
1463 The *follow_symlinks* argument.
1464
Georg Brandl116aa622007-08-15 14:28:22 +00001465
Larry Hastings9cf065c2012-06-22 16:30:09 -07001466.. function:: chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001467
1468 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001469 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl116aa622007-08-15 14:28:22 +00001470 combinations of them:
1471
Alexandre Vassalottic22c6f22009-07-21 00:51:58 +00001472 * :data:`stat.S_ISUID`
1473 * :data:`stat.S_ISGID`
1474 * :data:`stat.S_ENFMT`
1475 * :data:`stat.S_ISVTX`
1476 * :data:`stat.S_IREAD`
1477 * :data:`stat.S_IWRITE`
1478 * :data:`stat.S_IEXEC`
1479 * :data:`stat.S_IRWXU`
1480 * :data:`stat.S_IRUSR`
1481 * :data:`stat.S_IWUSR`
1482 * :data:`stat.S_IXUSR`
1483 * :data:`stat.S_IRWXG`
1484 * :data:`stat.S_IRGRP`
1485 * :data:`stat.S_IWGRP`
1486 * :data:`stat.S_IXGRP`
1487 * :data:`stat.S_IRWXO`
1488 * :data:`stat.S_IROTH`
1489 * :data:`stat.S_IWOTH`
1490 * :data:`stat.S_IXOTH`
Georg Brandl116aa622007-08-15 14:28:22 +00001491
Georg Brandl50c40002012-06-24 11:45:20 +02001492 This function can support :ref:`specifying a file descriptor <path_fd>`,
1493 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
1494 following symlinks <follow_symlinks>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001495
Georg Brandlc575c902008-09-13 17:46:05 +00001496 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001497
1498 .. note::
1499
Georg Brandl50c40002012-06-24 11:45:20 +02001500 Although Windows supports :func:`chmod`, you can only set the file's
1501 read-only flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
1502 constants or a corresponding integer value). All other bits are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +00001503
Larry Hastings9cf065c2012-06-22 16:30:09 -07001504 .. versionadded:: 3.3
1505 Added support for specifying *path* as an open file descriptor,
1506 and the *dir_fd* and *follow_symlinks* arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001507
Larry Hastings9cf065c2012-06-22 16:30:09 -07001508
1509.. function:: chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001510
Georg Brandl50c40002012-06-24 11:45:20 +02001511 Change the owner and group id of *path* to the numeric *uid* and *gid*. To
1512 leave one of the ids unchanged, set it to -1.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001513
Georg Brandl50c40002012-06-24 11:45:20 +02001514 This function can support :ref:`specifying a file descriptor <path_fd>`,
1515 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
1516 following symlinks <follow_symlinks>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001517
Sandro Tosid902a142011-08-22 23:28:27 +02001518 See :func:`shutil.chown` for a higher-level function that accepts names in
1519 addition to numeric ids.
1520
Benjamin Petersonf650e462010-05-06 23:03:05 +00001521 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001522
Larry Hastings9cf065c2012-06-22 16:30:09 -07001523 .. versionadded:: 3.3
1524 Added support for specifying an open file descriptor for *path*,
1525 and the *dir_fd* and *follow_symlinks* arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001526
Benjamin Peterson799bd802011-08-31 22:15:17 -04001527
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001528.. function:: chroot(path)
1529
Georg Brandl8a5555f2012-06-24 13:29:09 +02001530 Change the root directory of the current process to *path*.
1531
1532 Availability: Unix.
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001533
1534
1535.. function:: fchdir(fd)
1536
1537 Change the current working directory to the directory represented by the file
1538 descriptor *fd*. The descriptor must refer to an opened directory, not an
Georg Brandl4d399a42012-06-25 07:40:32 +02001539 open file. As of Python 3.3, this is equivalent to ``os.chdir(fd)``.
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001540
1541 Availability: Unix.
1542
1543
1544.. function:: getcwd()
1545
1546 Return a string representing the current working directory.
1547
1548 Availability: Unix, Windows.
1549
1550
1551.. function:: getcwdb()
1552
1553 Return a bytestring representing the current working directory.
1554
1555 Availability: Unix, Windows.
1556
1557
Georg Brandl116aa622007-08-15 14:28:22 +00001558.. function:: lchflags(path, flags)
1559
Georg Brandl50c40002012-06-24 11:45:20 +02001560 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do
Georg Brandl4d399a42012-06-25 07:40:32 +02001561 not follow symbolic links. As of Python 3.3, this is equivalent to
Georg Brandlb9df00c2012-06-24 12:38:14 +02001562 ``os.chflags(path, flags, follow_symlinks=False)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001563
1564 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001565
Georg Brandl116aa622007-08-15 14:28:22 +00001566
Christian Heimes93852662007-12-01 12:22:32 +00001567.. function:: lchmod(path, mode)
1568
1569 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
Georg Brandl50c40002012-06-24 11:45:20 +02001570 affects the symlink rather than the target. See the docs for :func:`chmod`
Georg Brandl4d399a42012-06-25 07:40:32 +02001571 for possible values of *mode*. As of Python 3.3, this is equivalent to
Georg Brandlb9df00c2012-06-24 12:38:14 +02001572 ``os.chmod(path, mode, follow_symlinks=False)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001573
1574 Availability: Unix.
Christian Heimes93852662007-12-01 12:22:32 +00001575
Christian Heimes93852662007-12-01 12:22:32 +00001576
Georg Brandl116aa622007-08-15 14:28:22 +00001577.. function:: lchown(path, uid, gid)
1578
Georg Brandl50c40002012-06-24 11:45:20 +02001579 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Georg Brandl4d399a42012-06-25 07:40:32 +02001580 function will not follow symbolic links. As of Python 3.3, this is equivalent
Georg Brandlb9df00c2012-06-24 12:38:14 +02001581 to ``os.chown(path, uid, gid, follow_symlinks=False)``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001582
1583 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001584
Georg Brandl116aa622007-08-15 14:28:22 +00001585
Larry Hastings9cf065c2012-06-22 16:30:09 -07001586.. function:: link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001587
Larry Hastings9cf065c2012-06-22 16:30:09 -07001588 Create a hard link pointing to *src* named *dst*.
Benjamin Peterson799bd802011-08-31 22:15:17 -04001589
Georg Brandlaceaf902012-06-25 08:33:56 +02001590 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
1591 supply :ref:`paths relative to directory descriptors <dir_fd>`, and :ref:`not
1592 following symlinks <follow_symlinks>`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001593
Brian Curtin1b9df392010-11-24 20:24:31 +00001594 Availability: Unix, Windows.
1595
1596 .. versionchanged:: 3.2
1597 Added Windows support.
Georg Brandl116aa622007-08-15 14:28:22 +00001598
Larry Hastings9cf065c2012-06-22 16:30:09 -07001599 .. versionadded:: 3.3
1600 Added the *src_dir_fd*, *dst_dir_fd*, and *follow_symlinks* arguments.
1601
Georg Brandl116aa622007-08-15 14:28:22 +00001602
Martin v. Löwis9c71f902010-07-24 10:09:11 +00001603.. function:: listdir(path='.')
Georg Brandl116aa622007-08-15 14:28:22 +00001604
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001605 Return a list containing the names of the entries in the directory given by
Larry Hastingsfdaea062012-06-25 04:42:23 -07001606 *path*. The list is in arbitrary order, and does not include the special
1607 entries ``'.'`` and ``'..'`` even if they are present in the directory.
Georg Brandl116aa622007-08-15 14:28:22 +00001608
Larry Hastingsfdaea062012-06-25 04:42:23 -07001609 *path* may be either of type ``str`` or of type ``bytes``. If *path*
1610 is of type ``bytes``, the filenames returned will also be of type ``bytes``;
1611 in all other circumstances, they will be of type ``str``.
Georg Brandl116aa622007-08-15 14:28:22 +00001612
Larry Hastings77892dc2012-06-25 03:27:33 -07001613 This function can also support :ref:`specifying a file descriptor
1614 <path_fd>`; the file descriptor must refer to a directory.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001615
Larry Hastingsfdaea062012-06-25 04:42:23 -07001616 .. note::
1617 To encode ``str`` filenames to ``bytes``, use :func:`~os.fsencode`.
1618
Benjamin Petersonf650e462010-05-06 23:03:05 +00001619 Availability: Unix, Windows.
1620
Victor Stinner6036e442015-03-08 01:58:04 +01001621 .. seealso::
1622
1623 The :func:`scandir` function returns the directory entries with more
1624 information than just the name.
1625
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +00001626 .. versionchanged:: 3.2
1627 The *path* parameter became optional.
Georg Brandl116aa622007-08-15 14:28:22 +00001628
Larry Hastings9cf065c2012-06-22 16:30:09 -07001629 .. versionadded:: 3.3
1630 Added support for specifying an open file descriptor for *path*.
Benjamin Peterson799bd802011-08-31 22:15:17 -04001631
Georg Brandl50c40002012-06-24 11:45:20 +02001632
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02001633.. function:: lstat(path, \*, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001634
R. David Murray7b1aae92011-01-24 19:34:58 +00001635 Perform the equivalent of an :c:func:`lstat` system call on the given path.
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02001636 Similar to :func:`~os.stat`, but does not follow symbolic links. Return a
1637 :class:`stat_result` object.
1638
1639 On platforms that do not support symbolic links, this is an alias for
1640 :func:`~os.stat`.
1641
1642 As of Python 3.3, this is equivalent to ``os.stat(path, dir_fd=dir_fd,
1643 follow_symlinks=False)``.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001644
Georg Brandl50c40002012-06-24 11:45:20 +02001645 This function can also support :ref:`paths relative to directory descriptors
1646 <dir_fd>`.
Brian Curtinc7395692010-07-09 15:15:09 +00001647
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02001648 .. seealso::
1649
Berker Peksag2034caa2015-04-27 13:53:28 +03001650 The :func:`.stat` function.
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02001651
Georg Brandlb3823372010-07-10 08:58:37 +00001652 .. versionchanged:: 3.2
1653 Added support for Windows 6.0 (Vista) symbolic links.
Georg Brandl116aa622007-08-15 14:28:22 +00001654
Larry Hastings9cf065c2012-06-22 16:30:09 -07001655 .. versionchanged:: 3.3
1656 Added the *dir_fd* parameter.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001657
1658
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001659.. function:: mkdir(path, mode=0o777, *, dir_fd=None)
1660
1661 Create a directory named *path* with numeric mode *mode*.
1662
1663 On some systems, *mode* is ignored. Where it is used, the current umask
1664 value is first masked out. If the directory already exists, :exc:`OSError`
1665 is raised.
1666
1667 This function can also support :ref:`paths relative to directory descriptors
1668 <dir_fd>`.
1669
1670 It is also possible to create temporary directories; see the
1671 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1672
1673 Availability: Unix, Windows.
1674
1675 .. versionadded:: 3.3
1676 The *dir_fd* argument.
1677
1678
Zachary Warea22ae212014-03-20 09:42:01 -05001679.. function:: makedirs(name, mode=0o777, exist_ok=False)
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001680
1681 .. index::
1682 single: directory; creating
1683 single: UNC paths; and os.makedirs()
1684
1685 Recursive directory creation function. Like :func:`mkdir`, but makes all
Hynek Schlawack0230b6a2012-10-07 18:04:38 +02001686 intermediate-level directories needed to contain the leaf directory.
1687
1688 The default *mode* is ``0o777`` (octal). On some systems, *mode* is
1689 ignored. Where it is used, the current umask value is first masked out.
1690
Benjamin Petersonee5f1c12014-04-01 19:13:18 -04001691 If *exist_ok* is ``False`` (the default), an :exc:`OSError` is raised if the
1692 target directory already exists.
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001693
1694 .. note::
1695
1696 :func:`makedirs` will become confused if the path elements to create
Hynek Schlawack0230b6a2012-10-07 18:04:38 +02001697 include :data:`pardir` (eg. ".." on UNIX systems).
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001698
1699 This function handles UNC paths correctly.
1700
1701 .. versionadded:: 3.2
1702 The *exist_ok* parameter.
1703
Benjamin Peterson1acc69c2014-04-01 19:22:06 -04001704 .. versionchanged:: 3.4.1
Benjamin Petersonee5f1c12014-04-01 19:13:18 -04001705
Benjamin Peterson1acc69c2014-04-01 19:22:06 -04001706 Before Python 3.4.1, if *exist_ok* was ``True`` and the directory existed,
Benjamin Petersonee5f1c12014-04-01 19:13:18 -04001707 :func:`makedirs` would still raise an error if *mode* did not match the
1708 mode of the existing directory. Since this behavior was impossible to
Benjamin Peterson1acc69c2014-04-01 19:22:06 -04001709 implement safely, it was removed in Python 3.4.1. See :issue:`21082`.
Benjamin Peterson4717e212014-04-01 19:17:57 -04001710
Georg Brandl8ccadaa2012-06-24 12:50:06 +02001711
Larry Hastings9cf065c2012-06-22 16:30:09 -07001712.. function:: mkfifo(path, mode=0o666, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001713
Larry Hastings9cf065c2012-06-22 16:30:09 -07001714 Create a FIFO (a named pipe) named *path* with numeric mode *mode*.
1715 The current umask value is first masked out from the mode.
1716
Georg Brandl50c40002012-06-24 11:45:20 +02001717 This function can also support :ref:`paths relative to directory descriptors
1718 <dir_fd>`.
Georg Brandl116aa622007-08-15 14:28:22 +00001719
1720 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
1721 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
1722 rendezvous between "client" and "server" type processes: the server opens the
1723 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
1724 doesn't open the FIFO --- it just creates the rendezvous point.
1725
Benjamin Petersonf650e462010-05-06 23:03:05 +00001726 Availability: Unix.
1727
Larry Hastings9cf065c2012-06-22 16:30:09 -07001728 .. versionadded:: 3.3
1729 The *dir_fd* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001730
Larry Hastings9cf065c2012-06-22 16:30:09 -07001731
1732.. function:: mknod(filename, mode=0o600, device=0, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001733
1734 Create a filesystem node (file, device special file or named pipe) named
Georg Brandl18244152009-09-02 20:34:52 +00001735 *filename*. *mode* specifies both the permissions to use and the type of node
1736 to be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
1737 ``stat.S_IFCHR``, ``stat.S_IFBLK``, and ``stat.S_IFIFO`` (those constants are
1738 available in :mod:`stat`). For ``stat.S_IFCHR`` and ``stat.S_IFBLK``,
1739 *device* defines the newly created device special file (probably using
Georg Brandl116aa622007-08-15 14:28:22 +00001740 :func:`os.makedev`), otherwise it is ignored.
1741
Georg Brandl50c40002012-06-24 11:45:20 +02001742 This function can also support :ref:`paths relative to directory descriptors
1743 <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001744
1745 .. versionadded:: 3.3
1746 The *dir_fd* argument.
1747
Georg Brandl116aa622007-08-15 14:28:22 +00001748
1749.. function:: major(device)
1750
Christian Heimesfaf2f632008-01-06 16:59:19 +00001751 Extract the device major number from a raw device number (usually the
Georg Brandl60203b42010-10-06 10:11:56 +00001752 :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).
Georg Brandl116aa622007-08-15 14:28:22 +00001753
Georg Brandl116aa622007-08-15 14:28:22 +00001754
1755.. function:: minor(device)
1756
Christian Heimesfaf2f632008-01-06 16:59:19 +00001757 Extract the device minor number from a raw device number (usually the
Georg Brandl60203b42010-10-06 10:11:56 +00001758 :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).
Georg Brandl116aa622007-08-15 14:28:22 +00001759
Georg Brandl116aa622007-08-15 14:28:22 +00001760
1761.. function:: makedev(major, minor)
1762
Christian Heimesfaf2f632008-01-06 16:59:19 +00001763 Compose a raw device number from the major and minor device numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001764
Georg Brandl116aa622007-08-15 14:28:22 +00001765
Georg Brandl116aa622007-08-15 14:28:22 +00001766.. function:: pathconf(path, name)
1767
1768 Return system configuration information relevant to a named file. *name*
1769 specifies the configuration value to retrieve; it may be a string which is the
1770 name of a defined system value; these names are specified in a number of
1771 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1772 additional names as well. The names known to the host operating system are
1773 given in the ``pathconf_names`` dictionary. For configuration variables not
1774 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00001775
1776 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1777 specific value for *name* is not supported by the host system, even if it is
1778 included in ``pathconf_names``, an :exc:`OSError` is raised with
1779 :const:`errno.EINVAL` for the error number.
1780
Larry Hastings77892dc2012-06-25 03:27:33 -07001781 This function can support :ref:`specifying a file descriptor
Georg Brandl306336b2012-06-24 12:55:33 +02001782 <path_fd>`.
1783
Benjamin Petersonf650e462010-05-06 23:03:05 +00001784 Availability: Unix.
1785
Georg Brandl116aa622007-08-15 14:28:22 +00001786
1787.. data:: pathconf_names
1788
1789 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1790 the integer values defined for those names by the host operating system. This
Georg Brandl8a5555f2012-06-24 13:29:09 +02001791 can be used to determine the set of names known to the system.
1792
1793 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001794
1795
Larry Hastings9cf065c2012-06-22 16:30:09 -07001796.. function:: readlink(path, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001797
1798 Return a string representing the path to which the symbolic link points. The
Georg Brandl50c40002012-06-24 11:45:20 +02001799 result may be either an absolute or relative pathname; if it is relative, it
1800 may be converted to an absolute pathname using
1801 ``os.path.join(os.path.dirname(path), result)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001802
Georg Brandl76e55382008-10-08 16:34:57 +00001803 If the *path* is a string object, the result will also be a string object,
1804 and the call may raise an UnicodeDecodeError. If the *path* is a bytes
1805 object, the result will be a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +00001806
Georg Brandl50c40002012-06-24 11:45:20 +02001807 This function can also support :ref:`paths relative to directory descriptors
1808 <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001809
Brian Curtinc7395692010-07-09 15:15:09 +00001810 Availability: Unix, Windows
1811
Georg Brandlb3823372010-07-10 08:58:37 +00001812 .. versionchanged:: 3.2
1813 Added support for Windows 6.0 (Vista) symbolic links.
Georg Brandl116aa622007-08-15 14:28:22 +00001814
Larry Hastings9cf065c2012-06-22 16:30:09 -07001815 .. versionadded:: 3.3
1816 The *dir_fd* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001817
Georg Brandl116aa622007-08-15 14:28:22 +00001818
Larry Hastingsb698d8e2012-06-23 16:55:07 -07001819.. function:: remove(path, *, dir_fd=None)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001820
Georg Brandl50c40002012-06-24 11:45:20 +02001821 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
1822 raised. Use :func:`rmdir` to remove directories.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001823
Georg Brandl50c40002012-06-24 11:45:20 +02001824 This function can support :ref:`paths relative to directory descriptors
1825 <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001826
1827 On Windows, attempting to remove a file that is in use causes an exception to
1828 be raised; on Unix, the directory entry is removed but the storage allocated
1829 to the file is not made available until the original file is no longer in use.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001830
Larry Hastingsb698d8e2012-06-23 16:55:07 -07001831 This function is identical to :func:`unlink`.
1832
Benjamin Petersonf650e462010-05-06 23:03:05 +00001833 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001834
Larry Hastings9cf065c2012-06-22 16:30:09 -07001835 .. versionadded:: 3.3
Larry Hastingsb698d8e2012-06-23 16:55:07 -07001836 The *dir_fd* argument.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001837
Georg Brandl116aa622007-08-15 14:28:22 +00001838
Zachary Warea22ae212014-03-20 09:42:01 -05001839.. function:: removedirs(name)
Georg Brandl116aa622007-08-15 14:28:22 +00001840
1841 .. index:: single: directory; deleting
1842
Christian Heimesfaf2f632008-01-06 16:59:19 +00001843 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl116aa622007-08-15 14:28:22 +00001844 leaf directory is successfully removed, :func:`removedirs` tries to
1845 successively remove every parent directory mentioned in *path* until an error
1846 is raised (which is ignored, because it generally means that a parent directory
1847 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1848 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1849 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1850 successfully removed.
1851
Georg Brandl116aa622007-08-15 14:28:22 +00001852
Larry Hastings9cf065c2012-06-22 16:30:09 -07001853.. function:: rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001854
1855 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1856 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Christian Heimesfaf2f632008-01-06 16:59:19 +00001857 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl116aa622007-08-15 14:28:22 +00001858 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1859 the renaming will be an atomic operation (this is a POSIX requirement). On
1860 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01001861 file.
1862
Georg Brandlaceaf902012-06-25 08:33:56 +02001863 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
1864 supply :ref:`paths relative to directory descriptors <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001865
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01001866 If you want cross-platform overwriting of the destination, use :func:`replace`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001867
1868 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001869
Larry Hastings9cf065c2012-06-22 16:30:09 -07001870 .. versionadded:: 3.3
1871 The *src_dir_fd* and *dst_dir_fd* arguments.
1872
Georg Brandl116aa622007-08-15 14:28:22 +00001873
1874.. function:: renames(old, new)
1875
1876 Recursive directory or file renaming function. Works like :func:`rename`, except
1877 creation of any intermediate directories needed to make the new pathname good is
1878 attempted first. After the rename, directories corresponding to rightmost path
1879 segments of the old name will be pruned away using :func:`removedirs`.
1880
Georg Brandl116aa622007-08-15 14:28:22 +00001881 .. note::
1882
1883 This function can fail with the new directory structure made if you lack
1884 permissions needed to remove the leaf directory or file.
1885
1886
Larry Hastings9cf065c2012-06-22 16:30:09 -07001887.. function:: replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01001888
1889 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1890 :exc:`OSError` will be raised. If *dst* exists and is a file, it will
1891 be replaced silently if the user has permission. The operation may fail
1892 if *src* and *dst* are on different filesystems. If successful,
1893 the renaming will be an atomic operation (this is a POSIX requirement).
1894
Georg Brandlaceaf902012-06-25 08:33:56 +02001895 This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
1896 supply :ref:`paths relative to directory descriptors <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07001897
Georg Brandl8a5555f2012-06-24 13:29:09 +02001898 Availability: Unix, Windows.
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01001899
1900 .. versionadded:: 3.3
1901
1902
Larry Hastingsb698d8e2012-06-23 16:55:07 -07001903.. function:: rmdir(path, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001904
Georg Brandla6053b42009-09-01 08:11:14 +00001905 Remove (delete) the directory *path*. Only works when the directory is
1906 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
Benjamin Petersonf650e462010-05-06 23:03:05 +00001907 directory trees, :func:`shutil.rmtree` can be used.
1908
Georg Brandl50c40002012-06-24 11:45:20 +02001909 This function can support :ref:`paths relative to directory descriptors
1910 <dir_fd>`.
Larry Hastingsb698d8e2012-06-23 16:55:07 -07001911
Benjamin Petersonf650e462010-05-06 23:03:05 +00001912 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001913
Larry Hastingsb698d8e2012-06-23 16:55:07 -07001914 .. versionadded:: 3.3
1915 The *dir_fd* parameter.
1916
Georg Brandl116aa622007-08-15 14:28:22 +00001917
Victor Stinner6036e442015-03-08 01:58:04 +01001918.. function:: scandir(path='.')
1919
1920 Return an iterator of :class:`DirEntry` objects corresponding to the entries
1921 in the directory given by *path*. The entries are yielded in arbitrary
1922 order, and the special entries ``'.'`` and ``'..'`` are not included.
1923
1924 On Windows, *path* must of type :class:`str`. On POSIX, *path* can be of
1925 type :class:`str` or :class:`bytes`. If *path* is of type :class:`bytes`,
1926 the :attr:`~DirEntry.name` and :attr:`~DirEntry.path` attributes of
1927 :class:`DirEntry` are also of type ``bytes``. Use :func:`~os.fsencode` and
1928 :func:`~os.fsdecode` to encode and decode paths.
1929
1930 The :func:`scandir` function is recommended, instead of :func:`listdir`,
1931 when the file type of entries is used. In most cases, the file type of a
1932 :class:`DirEntry` is retrieved directly by :func:`scandir`, no system call
1933 is required. If only the name of entries is used, :func:`listdir` can
1934 be more efficient than :func:`scandir`.
1935
1936 The following example shows a simple use of :func:`scandir` to display all
1937 the files excluding directories in the given *path* that don't start with
1938 ``'.'``::
1939
1940 for entry in os.scandir(path):
1941 if not entry.name.startswith('.') and entry.is_file():
1942 print(entry.name)
1943
1944 .. note::
1945
1946 On Unix-based systems, :func:`scandir` uses the system's
1947 `opendir() <http://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html>`_
1948 and
1949 `readdir() <http://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html>`_
1950 functions. On Windows, it uses the Win32
1951 `FindFirstFileW <http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx>`_
1952 and
1953 `FindNextFileW <http://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx>`_
1954 functions.
1955
1956 .. seealso::
1957
1958 The :func:`listdir` function returns the names of the directory entries.
1959
1960 .. versionadded:: 3.5
1961
1962
1963.. class:: DirEntry
1964
1965 Object yielded by :func:`scandir` to expose the file path and other file
1966 attributes of a directory entry.
1967
1968 :func:`scandir` will provide as much of this information as possible without
1969 making additional system calls. When a ``stat()`` or ``lstat()`` system call
1970 is made, the ``DirEntry`` object cache the result .
1971
1972 ``DirEntry`` instances are not intended to be stored in long-lived data
1973 structures; if you know the file metadata has changed or if a long time has
1974 elapsed since calling :func:`scandir`, call ``os.stat(entry.path)`` to fetch
1975 up-to-date information.
1976
1977 Because the ``DirEntry`` methods can make operating system calls, they may
1978 also raise :exc:`OSError`. For example, if a file is deleted between calling
1979 :func:`scandir` and calling :func:`DirEntry.stat`, a
1980 :exc:`FileNotFoundError` exception can be raised. Unfortunately, the
1981 behaviour on errors depends on the platform. If you need very fine-grained
1982 control over errors, you can catch :exc:`OSError` when calling one of the
1983 ``DirEntry`` methods and handle as appropriate.
1984
1985 Attributes and methods on a ``DirEntry`` instance are as follows:
1986
1987 .. attribute:: name
1988
1989 The entry's base filename, relative to the :func:`scandir` *path*
1990 argument.
1991
1992 The :attr:`name` type is :class:`str`. On POSIX, it can be of type
1993 :class:`bytes` if the type of the :func:`scandir` *path* argument is also
1994 :class:`bytes`. Use :func:`~os.fsdecode` to decode the name.
1995
1996 .. attribute:: path
1997
1998 The entry's full path name: equivalent to ``os.path.join(scandir_path,
1999 entry.name)`` where *scandir_path* is the :func:`scandir` *path*
2000 argument. The path is only absolute if the :func:`scandir` *path*
2001 argument is absolute.
2002
2003 The :attr:`name` type is :class:`str`. On POSIX, it can be of type
2004 :class:`bytes` if the type of the :func:`scandir` *path* argument is also
2005 :class:`bytes`. Use :func:`~os.fsdecode` to decode the path.
2006
2007 .. method:: inode()
2008
2009 Return the inode number of the entry.
2010
2011 The result is cached in the object, use ``os.stat(entry.path,
2012 follow_symlinks=False).st_ino`` to fetch up-to-date information.
2013
2014 On POSIX, no system call is required.
2015
2016 .. method:: is_dir(\*, follow_symlinks=True)
2017
2018 If *follow_symlinks* is ``True`` (the default), return ``True`` if the
2019 entry is a directory or a symbolic link pointing to a directory,
2020 return ``False`` if it points to another kind of file, if it doesn't
2021 exist anymore or if it is a broken symbolic link.
2022
2023 If *follow_symlinks* is ``False``, return ``True`` only if this entry
2024 is a directory, return ``False`` if it points to a symbolic link or
2025 another kind of file, if the entry doesn't exist anymore or if it is a
2026 broken symbolic link
2027
2028 The result is cached in the object. Call :func:`stat.S_ISDIR` with
2029 :func:`os.stat` to fetch up-to-date information.
2030
2031 The method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2032 but :exc:`FileNotFoundError` is catched.
2033
2034 In most cases, no system call is required.
2035
2036 .. method:: is_file(\*, follow_symlinks=True)
2037
2038 If *follow_symlinks* is ``True`` (the default), return ``True`` if the
2039 entry is a regular file or a symbolic link pointing to a regular file,
2040 return ``False`` if it points to another kind of file, if it doesn't
2041 exist anymore or if it is a broken symbolic link.
2042
2043 If *follow_symlinks* is ``False``, return ``True`` only if this entry
2044 is a regular file, return ``False`` if it points to a symbolic link or
2045 another kind of file, if it doesn't exist anymore or if it is a broken
2046 symbolic link.
2047
2048 The result is cached in the object. Call :func:`stat.S_ISREG` with
2049 :func:`os.stat` to fetch up-to-date information.
2050
2051 The method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2052 but :exc:`FileNotFoundError` is catched.
2053
2054 In most cases, no system call is required.
2055
2056 .. method:: is_symlink()
2057
2058 Return ``True`` if this entry is a symbolic link or a broken symbolic
2059 link, return ``False`` if it points to a another kind of file or if the
2060 entry doesn't exist anymore.
2061
2062 The result is cached in the object. Call :func:`os.path.islink` to fetch
2063 up-to-date information.
2064
2065 The method can raise :exc:`OSError`, such as :exc:`PermissionError`,
2066 but :exc:`FileNotFoundError` is catched.
2067
2068 In most cases, no system call is required.
2069
2070 .. method:: stat(\*, follow_symlinks=True)
2071
2072 Return a :class:`stat_result` object for this entry. This function
2073 normally follows symbolic links; to stat a symbolic link add the
2074 argument ``follow_symlinks=False``.
2075
2076 On Windows, the ``st_ino``, ``st_dev`` and ``st_nlink`` attributes of the
2077 :class:`stat_result` are always set to zero. Call :func:`os.stat` to
2078 get these attributes.
2079
2080 The result is cached in the object. Call :func:`os.stat` to fetch
2081 up-to-date information.
2082
2083 On Windows, ``DirEntry.stat(follow_symlinks=False)`` doesn't require a
2084 system call. ``DirEntry.stat()`` requires a system call if the entry is a
2085 symbolic link.
2086
2087 .. versionadded:: 3.5
2088
2089
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002090.. function:: stat(path, \*, dir_fd=None, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00002091
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002092 Get the status of a file or a file descriptor. Perform the equivalent of a
2093 :c:func:`stat` system call on the given path. *path* may be specified as
2094 either a string or as an open file descriptor. Return a :class:`stat_result`
2095 object.
Georg Brandl116aa622007-08-15 14:28:22 +00002096
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002097 This function normally follows symlinks; to stat a symlink add the argument
2098 ``follow_symlinks=False``, or use :func:`lstat`.
R. David Murray7b1aae92011-01-24 19:34:58 +00002099
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002100 This function can support :ref:`specifying a file descriptor <path_fd>` and
2101 :ref:`not following symlinks <follow_symlinks>`.
Georg Brandl116aa622007-08-15 14:28:22 +00002102
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002103 .. index:: module: stat
R. David Murray7b1aae92011-01-24 19:34:58 +00002104
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002105 Example::
Georg Brandl116aa622007-08-15 14:28:22 +00002106
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002107 >>> import os
2108 >>> statinfo = os.stat('somefile.txt')
2109 >>> statinfo
2110 os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
2111 st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
2112 st_mtime=1297230027, st_ctime=1297230027)
2113 >>> statinfo.st_size
2114 264
R. David Murray7b1aae92011-01-24 19:34:58 +00002115
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002116 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002117
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002118 .. seealso::
Zachary Ware63f277b2014-06-19 09:46:37 -05002119
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002120 :func:`fstat` and :func:`lstat` functions.
2121
2122 .. versionadded:: 3.3
2123 Added the *dir_fd* and *follow_symlinks* arguments, specifying a file
2124 descriptor instead of a path.
2125
2126
2127.. class:: stat_result
2128
2129 Object whose attributes correspond roughly to the members of the
2130 :c:type:`stat` structure. It is used for the result of :func:`os.stat`,
2131 :func:`os.fstat` and :func:`os.lstat`.
2132
2133 Attributes:
2134
2135 .. attribute:: st_mode
2136
2137 File mode: file type and file mode bits (permissions).
2138
2139 .. attribute:: st_ino
2140
2141 Inode number.
2142
2143 .. attribute:: st_dev
2144
2145 Identifier of the device on which this file resides.
2146
2147 .. attribute:: st_nlink
2148
2149 Number of hard links.
2150
2151 .. attribute:: st_uid
2152
2153 User identifier of the file owner.
2154
2155 .. attribute:: st_gid
2156
2157 Group identifier of the file owner.
2158
2159 .. attribute:: st_size
2160
2161 Size of the file in bytes, if it is a regular file or a symbolic link.
2162 The size of a symbolic link is the length of the pathname it contains,
2163 without a terminating null byte.
2164
2165 Timestamps:
2166
2167 .. attribute:: st_atime
2168
2169 Time of most recent access expressed in seconds.
2170
2171 .. attribute:: st_mtime
2172
2173 Time of most recent content modification expressed in seconds.
2174
2175 .. attribute:: st_ctime
2176
2177 Platform dependent:
2178
2179 * the time of most recent metadata change on Unix,
2180 * the time of creation on Windows, expressed in seconds.
2181
2182 .. attribute:: st_atime_ns
2183
2184 Time of most recent access expressed in nanoseconds as an integer.
2185
2186 .. attribute:: st_mtime_ns
2187
2188 Time of most recent content modification expressed in nanoseconds as an
2189 integer.
2190
2191 .. attribute:: st_ctime_ns
2192
2193 Platform dependent:
2194
2195 * the time of most recent metadata change on Unix,
2196 * the time of creation on Windows, expressed in nanoseconds as an
2197 integer.
2198
2199 See also the :func:`stat_float_times` function.
Zachary Ware63f277b2014-06-19 09:46:37 -05002200
Georg Brandl116aa622007-08-15 14:28:22 +00002201 .. note::
2202
Senthil Kumaran3aac1792011-07-04 11:43:51 -07002203 The exact meaning and resolution of the :attr:`st_atime`,
Senthil Kumarana6bac952011-07-04 11:28:30 -07002204 :attr:`st_mtime`, and :attr:`st_ctime` attributes depend on the operating
2205 system and the file system. For example, on Windows systems using the FAT
2206 or FAT32 file systems, :attr:`st_mtime` has 2-second resolution, and
2207 :attr:`st_atime` has only 1-day resolution. See your operating system
2208 documentation for details.
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002209
Larry Hastings6fe20b32012-04-19 15:07:49 -07002210 Similarly, although :attr:`st_atime_ns`, :attr:`st_mtime_ns`,
2211 and :attr:`st_ctime_ns` are always expressed in nanoseconds, many
2212 systems do not provide nanosecond precision. On systems that do
2213 provide nanosecond precision, the floating-point object used to
2214 store :attr:`st_atime`, :attr:`st_mtime`, and :attr:`st_ctime`
2215 cannot preserve all of it, and as such will be slightly inexact.
2216 If you need the exact timestamps you should always use
2217 :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and :attr:`st_ctime_ns`.
Georg Brandl116aa622007-08-15 14:28:22 +00002218
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002219 On some Unix systems (such as Linux), the following attributes may also be
2220 available:
2221
2222 .. attribute:: st_blocks
2223
2224 Number of 512-byte blocks allocated for file.
2225 This may be smaller than :attr:`st_size`/512 when the file has holes.
2226
2227 .. attribute:: st_blksize
2228
2229 "Preferred" blocksize for efficient file system I/O. Writing to a file in
2230 smaller chunks may cause an inefficient read-modify-rewrite.
2231
2232 .. attribute:: st_rdev
2233
2234 Type of device if an inode device.
2235
2236 .. attribute:: st_flags
2237
2238 User defined flags for file.
2239
2240 On other Unix systems (such as FreeBSD), the following attributes may be
2241 available (but may be only filled out if root tries to use them):
2242
2243 .. attribute:: st_gen
2244
2245 File generation number.
2246
2247 .. attribute:: st_birthtime
2248
2249 Time of file creation.
2250
2251 On Mac OS systems, the following attributes may also be available:
2252
2253 .. attribute:: st_rsize
2254
2255 Real size of the file.
2256
2257 .. attribute:: st_creator
2258
2259 Creator of the file.
2260
2261 .. attribute:: st_type
2262
2263 File type.
2264
Victor Stinnere1d24f72014-07-24 12:44:07 +02002265 On Windows systems, the following attribute is also available:
2266
2267 .. attribute:: st_file_attributes
2268
2269 Windows file attributes: ``dwFileAttributes`` member of the
2270 ``BY_HANDLE_FILE_INFORMATION`` structure returned by
2271 :c:func:`GetFileInformationByHandle`. See the ``FILE_ATTRIBUTE_*``
2272 constants in the :mod:`stat` module.
2273
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002274 The standard module :mod:`stat` defines functions and constants that are
2275 useful for extracting information from a :c:type:`stat` structure. (On
2276 Windows, some items are filled with dummy values.)
2277
2278 For backward compatibility, a :class:`stat_result` instance is also
Georg Brandl50c40002012-06-24 11:45:20 +02002279 accessible as a tuple of at least 10 integers giving the most important (and
2280 portable) members of the :c:type:`stat` structure, in the order
2281 :attr:`st_mode`, :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`,
2282 :attr:`st_uid`, :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`,
2283 :attr:`st_mtime`, :attr:`st_ctime`. More items may be added at the end by
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002284 some implementations. For compatibility with older Python versions,
2285 accessing :class:`stat_result` as a tuple always returns integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002286
Larry Hastings6fe20b32012-04-19 15:07:49 -07002287 .. versionadded:: 3.3
Victor Stinner6d4f4fe2014-07-24 12:42:16 +02002288 Added the :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and
2289 :attr:`st_ctime_ns` members.
Larry Hastings6fe20b32012-04-19 15:07:49 -07002290
Zachary Ware63f277b2014-06-19 09:46:37 -05002291 .. versionadded:: 3.5
2292 Added the :attr:`st_file_attributes` member on Windows.
2293
Georg Brandl116aa622007-08-15 14:28:22 +00002294
2295.. function:: stat_float_times([newvalue])
2296
2297 Determine whether :class:`stat_result` represents time stamps as float objects.
R. David Murray7b1aae92011-01-24 19:34:58 +00002298 If *newvalue* is ``True``, future calls to :func:`~os.stat` return floats, if it is
Georg Brandl116aa622007-08-15 14:28:22 +00002299 ``False``, future calls return ints. If *newvalue* is omitted, return the
2300 current setting.
2301
2302 For compatibility with older Python versions, accessing :class:`stat_result` as
2303 a tuple always returns integers.
2304
Georg Brandl55ac8f02007-09-01 13:51:09 +00002305 Python now returns float values by default. Applications which do not work
2306 correctly with floating point time stamps can use this function to restore the
2307 old behaviour.
Georg Brandl116aa622007-08-15 14:28:22 +00002308
2309 The resolution of the timestamps (that is the smallest possible fraction)
2310 depends on the system. Some systems only support second resolution; on these
2311 systems, the fraction will always be zero.
2312
2313 It is recommended that this setting is only changed at program startup time in
2314 the *__main__* module; libraries should never change this setting. If an
2315 application uses a library that works incorrectly if floating point time stamps
2316 are processed, this application should turn the feature off until the library
2317 has been corrected.
2318
Victor Stinner034d0aa2012-06-05 01:22:15 +02002319 .. deprecated:: 3.3
2320
Georg Brandl116aa622007-08-15 14:28:22 +00002321
2322.. function:: statvfs(path)
2323
Georg Brandl60203b42010-10-06 10:11:56 +00002324 Perform a :c:func:`statvfs` system call on the given path. The return value is
Georg Brandl116aa622007-08-15 14:28:22 +00002325 an object whose attributes describe the filesystem on the given path, and
Georg Brandl60203b42010-10-06 10:11:56 +00002326 correspond to the members of the :c:type:`statvfs` structure, namely:
Georg Brandl116aa622007-08-15 14:28:22 +00002327 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
2328 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
Benjamin Petersonf650e462010-05-06 23:03:05 +00002329 :attr:`f_flag`, :attr:`f_namemax`.
2330
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +00002331 Two module-level constants are defined for the :attr:`f_flag` attribute's
2332 bit-flags: if :const:`ST_RDONLY` is set, the filesystem is mounted
2333 read-only, and if :const:`ST_NOSUID` is set, the semantics of
2334 setuid/setgid bits are disabled or not supported.
2335
doko@ubuntu.comca616a22013-12-08 15:23:07 +01002336 Additional module-level constants are defined for GNU/glibc based systems.
2337 These are :const:`ST_NODEV` (disallow access to device special files),
2338 :const:`ST_NOEXEC` (disallow program execution), :const:`ST_SYNCHRONOUS`
2339 (writes are synced at once), :const:`ST_MANDLOCK` (allow mandatory locks on an FS),
2340 :const:`ST_WRITE` (write on file/directory/symlink), :const:`ST_APPEND`
2341 (append-only file), :const:`ST_IMMUTABLE` (immutable file), :const:`ST_NOATIME`
2342 (do not update access times), :const:`ST_NODIRATIME` (do not update directory access
2343 times), :const:`ST_RELATIME` (update atime relative to mtime/ctime).
2344
Georg Brandl50c40002012-06-24 11:45:20 +02002345 This function can support :ref:`specifying a file descriptor <path_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002346
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +00002347 .. versionchanged:: 3.2
2348 The :const:`ST_RDONLY` and :const:`ST_NOSUID` constants were added.
2349
doko@ubuntu.comca616a22013-12-08 15:23:07 +01002350 .. versionchanged:: 3.4
2351 The :const:`ST_NODEV`, :const:`ST_NOEXEC`, :const:`ST_SYNCHRONOUS`,
2352 :const:`ST_MANDLOCK`, :const:`ST_WRITE`, :const:`ST_APPEND`,
2353 :const:`ST_IMMUTABLE`, :const:`ST_NOATIME`, :const:`ST_NODIRATIME`,
2354 and :const:`ST_RELATIME` constants were added.
2355
Benjamin Petersonf650e462010-05-06 23:03:05 +00002356 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002357
Larry Hastings9cf065c2012-06-22 16:30:09 -07002358 .. versionadded:: 3.3
2359 Added support for specifying an open file descriptor for *path*.
Georg Brandl116aa622007-08-15 14:28:22 +00002360
Larry Hastings9cf065c2012-06-22 16:30:09 -07002361
2362.. data:: supports_dir_fd
2363
Serhiy Storchakadab83542013-10-13 20:12:43 +03002364 A :class:`~collections.abc.Set` object indicating which functions in the
Georg Brandlaceaf902012-06-25 08:33:56 +02002365 :mod:`os` module permit use of their *dir_fd* parameter. Different platforms
Larry Hastings9cf065c2012-06-22 16:30:09 -07002366 provide different functionality, and an option that might work on one might
2367 be unsupported on another. For consistency's sakes, functions that support
Andrew Svetlov5b898402012-12-18 21:26:36 +02002368 *dir_fd* always allow specifying the parameter, but will raise an exception
Larry Hastings9cf065c2012-06-22 16:30:09 -07002369 if the functionality is not actually available.
2370
2371 To check whether a particular function permits use of its *dir_fd*
2372 parameter, use the ``in`` operator on ``supports_dir_fd``. As an example,
2373 this expression determines whether the *dir_fd* parameter of :func:`os.stat`
2374 is locally available::
2375
2376 os.stat in os.supports_dir_fd
2377
Georg Brandlf62445a2012-06-24 13:31:20 +02002378 Currently *dir_fd* parameters only work on Unix platforms; none of them work
2379 on Windows.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002380
2381 .. versionadded:: 3.3
2382
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002383
Larry Hastings9cf065c2012-06-22 16:30:09 -07002384.. data:: supports_effective_ids
2385
Serhiy Storchakadab83542013-10-13 20:12:43 +03002386 A :class:`~collections.abc.Set` object indicating which functions in the
Georg Brandlaceaf902012-06-25 08:33:56 +02002387 :mod:`os` module permit use of the *effective_ids* parameter for
2388 :func:`os.access`. If the local platform supports it, the collection will
2389 contain :func:`os.access`, otherwise it will be empty.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002390
Georg Brandl50c40002012-06-24 11:45:20 +02002391 To check whether you can use the *effective_ids* parameter for
Berker Peksag4d6c6062015-02-16 03:36:10 +02002392 :func:`os.access`, use the ``in`` operator on ``supports_effective_ids``,
2393 like so::
Larry Hastings9cf065c2012-06-22 16:30:09 -07002394
2395 os.access in os.supports_effective_ids
2396
Georg Brandl50c40002012-06-24 11:45:20 +02002397 Currently *effective_ids* only works on Unix platforms; it does not work on
2398 Windows.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002399
2400 .. versionadded:: 3.3
2401
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002402
Larry Hastings9cf065c2012-06-22 16:30:09 -07002403.. data:: supports_fd
2404
Serhiy Storchakadab83542013-10-13 20:12:43 +03002405 A :class:`~collections.abc.Set` object indicating which functions in the
Georg Brandlaceaf902012-06-25 08:33:56 +02002406 :mod:`os` module permit specifying their *path* parameter as an open file
Larry Hastings9cf065c2012-06-22 16:30:09 -07002407 descriptor. Different platforms provide different functionality, and an
2408 option that might work on one might be unsupported on another. For
2409 consistency's sakes, functions that support *fd* always allow specifying
Andrew Svetlov5b898402012-12-18 21:26:36 +02002410 the parameter, but will raise an exception if the functionality is not
Larry Hastings9cf065c2012-06-22 16:30:09 -07002411 actually available.
2412
2413 To check whether a particular function permits specifying an open file
2414 descriptor for its *path* parameter, use the ``in`` operator on
2415 ``supports_fd``. As an example, this expression determines whether
2416 :func:`os.chdir` accepts open file descriptors when called on your local
2417 platform::
2418
2419 os.chdir in os.supports_fd
2420
2421 .. versionadded:: 3.3
2422
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002423
Larry Hastings9cf065c2012-06-22 16:30:09 -07002424.. data:: supports_follow_symlinks
2425
Serhiy Storchakadab83542013-10-13 20:12:43 +03002426 A :class:`~collections.abc.Set` object indicating which functions in the
Georg Brandlaceaf902012-06-25 08:33:56 +02002427 :mod:`os` module permit use of their *follow_symlinks* parameter. Different
Larry Hastings9cf065c2012-06-22 16:30:09 -07002428 platforms provide different functionality, and an option that might work on
2429 one might be unsupported on another. For consistency's sakes, functions that
2430 support *follow_symlinks* always allow specifying the parameter, but will
Andrew Svetlov5b898402012-12-18 21:26:36 +02002431 raise an exception if the functionality is not actually available.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002432
2433 To check whether a particular function permits use of its *follow_symlinks*
2434 parameter, use the ``in`` operator on ``supports_follow_symlinks``. As an
2435 example, this expression determines whether the *follow_symlinks* parameter
2436 of :func:`os.stat` is locally available::
2437
2438 os.stat in os.supports_follow_symlinks
2439
2440 .. versionadded:: 3.3
2441
Georg Brandl8ccadaa2012-06-24 12:50:06 +02002442
Larry Hastings9cf065c2012-06-22 16:30:09 -07002443.. function:: symlink(source, link_name, target_is_directory=False, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002444
Brian Curtinc7395692010-07-09 15:15:09 +00002445 Create a symbolic link pointing to *source* named *link_name*.
2446
Larry Hastings9cf065c2012-06-22 16:30:09 -07002447 On Windows, a symlink represents either a file or a directory, and does not
Jason R. Coombs3a092862013-05-27 23:21:28 -04002448 morph to the target dynamically. If the target is present, the type of the
2449 symlink will be created to match. Otherwise, the symlink will be created
2450 as a directory if *target_is_directory* is ``True`` or a file symlink (the
2451 default) otherwise. On non-Window platforms, *target_is_directory* is ignored.
Brian Curtind40e6f72010-07-08 21:39:08 +00002452
Georg Brandl64a41ed2010-10-06 08:52:48 +00002453 Symbolic link support was introduced in Windows 6.0 (Vista). :func:`symlink`
2454 will raise a :exc:`NotImplementedError` on Windows versions earlier than 6.0.
Brian Curtin52173d42010-12-02 18:29:18 +00002455
Georg Brandl50c40002012-06-24 11:45:20 +02002456 This function can support :ref:`paths relative to directory descriptors
2457 <dir_fd>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002458
Brian Curtin52173d42010-12-02 18:29:18 +00002459 .. note::
2460
Larry Hastings9cf065c2012-06-22 16:30:09 -07002461 On Windows, the *SeCreateSymbolicLinkPrivilege* is required in order to
2462 successfully create symlinks. This privilege is not typically granted to
2463 regular users but is available to accounts which can escalate privileges
2464 to the administrator level. Either obtaining the privilege or running your
Brian Curtin96245592010-12-28 17:08:22 +00002465 application as an administrator are ways to successfully create symlinks.
2466
Jason R. Coombs3a092862013-05-27 23:21:28 -04002467
Brian Curtin96245592010-12-28 17:08:22 +00002468 :exc:`OSError` is raised when the function is called by an unprivileged
2469 user.
Brian Curtind40e6f72010-07-08 21:39:08 +00002470
Georg Brandl64a41ed2010-10-06 08:52:48 +00002471 Availability: Unix, Windows.
Brian Curtinc7395692010-07-09 15:15:09 +00002472
Georg Brandlb3823372010-07-10 08:58:37 +00002473 .. versionchanged:: 3.2
2474 Added support for Windows 6.0 (Vista) symbolic links.
Georg Brandl116aa622007-08-15 14:28:22 +00002475
Larry Hastings9cf065c2012-06-22 16:30:09 -07002476 .. versionadded:: 3.3
2477 Added the *dir_fd* argument, and now allow *target_is_directory*
2478 on non-Windows platforms.
2479
Georg Brandl116aa622007-08-15 14:28:22 +00002480
Ross Lagerwall7807c352011-03-17 20:20:30 +02002481.. function:: sync()
2482
2483 Force write of everything to disk.
2484
2485 Availability: Unix.
2486
2487 .. versionadded:: 3.3
2488
2489
2490.. function:: truncate(path, length)
2491
2492 Truncate the file corresponding to *path*, so that it is at most
2493 *length* bytes in size.
2494
Georg Brandl306336b2012-06-24 12:55:33 +02002495 This function can support :ref:`specifying a file descriptor <path_fd>`.
2496
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002497 Availability: Unix, Windows.
Ross Lagerwall7807c352011-03-17 20:20:30 +02002498
2499 .. versionadded:: 3.3
2500
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002501 .. versionchanged:: 3.5
2502 Added support for Windows
Ross Lagerwall7807c352011-03-17 20:20:30 +02002503
Larry Hastingsb698d8e2012-06-23 16:55:07 -07002504.. function:: unlink(path, *, dir_fd=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002505
Larry Hastingsb698d8e2012-06-23 16:55:07 -07002506 Remove (delete) the file *path*. This function is identical to
Georg Brandl50c40002012-06-24 11:45:20 +02002507 :func:`remove`; the ``unlink`` name is its traditional Unix
Larry Hastings9cf065c2012-06-22 16:30:09 -07002508 name. Please see the documentation for :func:`remove` for
2509 further information.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002510
2511 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002512
Larry Hastings9cf065c2012-06-22 16:30:09 -07002513 .. versionadded:: 3.3
Larry Hastingsb698d8e2012-06-23 16:55:07 -07002514 The *dir_fd* parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00002515
Larry Hastings9cf065c2012-06-22 16:30:09 -07002516
2517.. function:: utime(path, times=None, *, ns=None, dir_fd=None, follow_symlinks=True)
Georg Brandl116aa622007-08-15 14:28:22 +00002518
Larry Hastings76ad59b2012-05-03 00:30:07 -07002519 Set the access and modified times of the file specified by *path*.
2520
2521 :func:`utime` takes two optional parameters, *times* and *ns*.
2522 These specify the times set on *path* and are used as follows:
2523
Larry Hastings9cf065c2012-06-22 16:30:09 -07002524 - If *ns* is not ``None``,
Larry Hastings76ad59b2012-05-03 00:30:07 -07002525 it must be a 2-tuple of the form ``(atime_ns, mtime_ns)``
2526 where each member is an int expressing nanoseconds.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002527 - If *times* is not ``None``,
Larry Hastings76ad59b2012-05-03 00:30:07 -07002528 it must be a 2-tuple of the form ``(atime, mtime)``
2529 where each member is an int or float expressing seconds.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002530 - If *times* and *ns* are both ``None``,
2531 this is equivalent to specifying ``ns=(atime_ns, mtime_ns)``
Larry Hastings76ad59b2012-05-03 00:30:07 -07002532 where both times are the current time.
Larry Hastings76ad59b2012-05-03 00:30:07 -07002533
Larry Hastings9cf065c2012-06-22 16:30:09 -07002534 It is an error to specify tuples for both *times* and *ns*.
Larry Hastings76ad59b2012-05-03 00:30:07 -07002535
2536 Whether a directory can be given for *path*
Brian Curtin52fbea12011-11-06 13:41:17 -06002537 depends on whether the operating system implements directories as files
2538 (for example, Windows does not). Note that the exact times you set here may
2539 not be returned by a subsequent :func:`~os.stat` call, depending on the
2540 resolution with which your operating system records access and modification
Larry Hastings76ad59b2012-05-03 00:30:07 -07002541 times; see :func:`~os.stat`. The best way to preserve exact times is to
2542 use the *st_atime_ns* and *st_mtime_ns* fields from the :func:`os.stat`
2543 result object with the *ns* parameter to `utime`.
Georg Brandl116aa622007-08-15 14:28:22 +00002544
Georg Brandl50c40002012-06-24 11:45:20 +02002545 This function can support :ref:`specifying a file descriptor <path_fd>`,
2546 :ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
2547 following symlinks <follow_symlinks>`.
Larry Hastings9cf065c2012-06-22 16:30:09 -07002548
Georg Brandlc575c902008-09-13 17:46:05 +00002549 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002550
Larry Hastings76ad59b2012-05-03 00:30:07 -07002551 .. versionadded:: 3.3
Larry Hastings9cf065c2012-06-22 16:30:09 -07002552 Added support for specifying an open file descriptor for *path*,
2553 and the *dir_fd*, *follow_symlinks*, and *ns* parameters.
Larry Hastings76ad59b2012-05-03 00:30:07 -07002554
Georg Brandl116aa622007-08-15 14:28:22 +00002555
Georg Brandl18244152009-09-02 20:34:52 +00002556.. function:: walk(top, topdown=True, onerror=None, followlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002557
2558 .. index::
2559 single: directory; walking
2560 single: directory; traversal
2561
Christian Heimesfaf2f632008-01-06 16:59:19 +00002562 Generate the file names in a directory tree by walking the tree
2563 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl116aa622007-08-15 14:28:22 +00002564 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
2565 filenames)``.
2566
2567 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
2568 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
2569 *filenames* is a list of the names of the non-directory files in *dirpath*.
2570 Note that the names in the lists contain no path components. To get a full path
2571 (which begins with *top*) to a file or directory in *dirpath*, do
2572 ``os.path.join(dirpath, name)``.
2573
Christian Heimesfaf2f632008-01-06 16:59:19 +00002574 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00002575 directory is generated before the triples for any of its subdirectories
Benjamin Petersone58e0c72014-06-15 20:51:12 -07002576 (directories are generated top-down). If *topdown* is ``False``, the triple
2577 for a directory is generated after the triples for all of its subdirectories
2578 (directories are generated bottom-up). No matter the value of *topdown*, the
2579 list of subdirectories is retrieved before the tuples for the directory and
2580 its subdirectories are generated.
Georg Brandl116aa622007-08-15 14:28:22 +00002581
Christian Heimesfaf2f632008-01-06 16:59:19 +00002582 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl116aa622007-08-15 14:28:22 +00002583 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
2584 recurse into the subdirectories whose names remain in *dirnames*; this can be
2585 used to prune the search, impose a specific order of visiting, or even to inform
2586 :func:`walk` about directories the caller creates or renames before it resumes
Christian Heimesfaf2f632008-01-06 16:59:19 +00002587 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl116aa622007-08-15 14:28:22 +00002588 ineffective, because in bottom-up mode the directories in *dirnames* are
2589 generated before *dirpath* itself is generated.
2590
Ezio Melotti67494f22011-10-18 12:59:39 +03002591 By default, errors from the :func:`listdir` call are ignored. If optional
Georg Brandl116aa622007-08-15 14:28:22 +00002592 argument *onerror* is specified, it should be a function; it will be called with
2593 one argument, an :exc:`OSError` instance. It can report the error to continue
2594 with the walk, or raise the exception to abort the walk. Note that the filename
2595 is available as the ``filename`` attribute of the exception object.
2596
2597 By default, :func:`walk` will not walk down into symbolic links that resolve to
Christian Heimesfaf2f632008-01-06 16:59:19 +00002598 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl116aa622007-08-15 14:28:22 +00002599 symlinks, on systems that support them.
2600
Georg Brandl116aa622007-08-15 14:28:22 +00002601 .. note::
2602
Georg Brandl50c40002012-06-24 11:45:20 +02002603 Be aware that setting *followlinks* to ``True`` can lead to infinite
2604 recursion if a link points to a parent directory of itself. :func:`walk`
2605 does not keep track of the directories it visited already.
Georg Brandl116aa622007-08-15 14:28:22 +00002606
2607 .. note::
2608
2609 If you pass a relative pathname, don't change the current working directory
2610 between resumptions of :func:`walk`. :func:`walk` never changes the current
2611 directory, and assumes that its caller doesn't either.
2612
2613 This example displays the number of bytes taken by non-directory files in each
2614 directory under the starting directory, except that it doesn't look under any
2615 CVS subdirectory::
2616
2617 import os
2618 from os.path import join, getsize
2619 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00002620 print(root, "consumes", end=" ")
2621 print(sum(getsize(join(root, name)) for name in files), end=" ")
2622 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00002623 if 'CVS' in dirs:
2624 dirs.remove('CVS') # don't visit CVS directories
2625
Victor Stinner47c41b42015-03-10 13:31:47 +01002626 In the next example (simple implementation of :func:`shutil.rmtree`),
2627 walking the tree bottom-up is essential, :func:`rmdir` doesn't allow
2628 deleting a directory before the directory is empty::
Georg Brandl116aa622007-08-15 14:28:22 +00002629
Christian Heimesfaf2f632008-01-06 16:59:19 +00002630 # Delete everything reachable from the directory named in "top",
Georg Brandl116aa622007-08-15 14:28:22 +00002631 # assuming there are no symbolic links.
2632 # CAUTION: This is dangerous! For example, if top == '/', it
2633 # could delete all your disk files.
2634 import os
2635 for root, dirs, files in os.walk(top, topdown=False):
2636 for name in files:
2637 os.remove(os.path.join(root, name))
2638 for name in dirs:
2639 os.rmdir(os.path.join(root, name))
2640
Victor Stinner524a5ba2015-03-10 13:20:34 +01002641 .. versionchanged:: 3.5
2642 The function now calls :func:`os.scandir` instead of :func:`os.listdir`.
2643 The usage of :func:`os.scandir` reduces the number of calls to
2644 :func:`os.stat`.
2645
Georg Brandl116aa622007-08-15 14:28:22 +00002646
Larry Hastingsb4038062012-07-15 10:57:38 -07002647.. function:: fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)
Charles-François Natali7372b062012-02-05 15:15:38 +01002648
2649 .. index::
2650 single: directory; walking
2651 single: directory; traversal
2652
Eli Benderskyd049d5c2012-02-11 09:52:29 +02002653 This behaves exactly like :func:`walk`, except that it yields a 4-tuple
Larry Hastingsc48fe982012-06-25 04:49:05 -07002654 ``(dirpath, dirnames, filenames, dirfd)``, and it supports ``dir_fd``.
Charles-François Natali7372b062012-02-05 15:15:38 +01002655
2656 *dirpath*, *dirnames* and *filenames* are identical to :func:`walk` output,
2657 and *dirfd* is a file descriptor referring to the directory *dirpath*.
2658
Larry Hastingsc48fe982012-06-25 04:49:05 -07002659 This function always supports :ref:`paths relative to directory descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -07002660 <dir_fd>` and :ref:`not following symlinks <follow_symlinks>`. Note however
Larry Hastings950b76a2012-07-15 17:32:36 -07002661 that, unlike other functions, the :func:`fwalk` default value for
Larry Hastingsb4038062012-07-15 10:57:38 -07002662 *follow_symlinks* is ``False``.
Larry Hastingsc48fe982012-06-25 04:49:05 -07002663
Charles-François Natali7372b062012-02-05 15:15:38 +01002664 .. note::
2665
2666 Since :func:`fwalk` yields file descriptors, those are only valid until
2667 the next iteration step, so you should duplicate them (e.g. with
2668 :func:`dup`) if you want to keep them longer.
2669
2670 This example displays the number of bytes taken by non-directory files in each
2671 directory under the starting directory, except that it doesn't look under any
2672 CVS subdirectory::
2673
2674 import os
2675 for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
2676 print(root, "consumes", end="")
Hynek Schlawack1729b8f2012-06-24 16:11:08 +02002677 print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
Charles-François Natali7372b062012-02-05 15:15:38 +01002678 end="")
2679 print("bytes in", len(files), "non-directory files")
2680 if 'CVS' in dirs:
2681 dirs.remove('CVS') # don't visit CVS directories
2682
2683 In the next example, walking the tree bottom-up is essential:
Victor Stinner69a6ca52012-08-05 15:18:02 +02002684 :func:`rmdir` doesn't allow deleting a directory before the directory is
Charles-François Natali7372b062012-02-05 15:15:38 +01002685 empty::
2686
2687 # Delete everything reachable from the directory named in "top",
2688 # assuming there are no symbolic links.
2689 # CAUTION: This is dangerous! For example, if top == '/', it
2690 # could delete all your disk files.
2691 import os
2692 for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
2693 for name in files:
Victor Stinner69a6ca52012-08-05 15:18:02 +02002694 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +01002695 for name in dirs:
Victor Stinner69a6ca52012-08-05 15:18:02 +02002696 os.rmdir(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +01002697
2698 Availability: Unix.
2699
2700 .. versionadded:: 3.3
2701
2702
Georg Brandlb9831ab2012-06-24 11:57:07 +02002703Linux extended attributes
2704~~~~~~~~~~~~~~~~~~~~~~~~~
2705
2706.. versionadded:: 3.3
2707
2708These functions are all available on Linux only.
2709
2710.. function:: getxattr(path, attribute, *, follow_symlinks=True)
2711
2712 Return the value of the extended filesystem attribute *attribute* for
2713 *path*. *attribute* can be bytes or str. If it is str, it is encoded
2714 with the filesystem encoding.
2715
2716 This function can support :ref:`specifying a file descriptor <path_fd>` and
2717 :ref:`not following symlinks <follow_symlinks>`.
2718
2719
2720.. function:: listxattr(path=None, *, follow_symlinks=True)
2721
2722 Return a list of the extended filesystem attributes on *path*. The
2723 attributes in the list are represented as strings decoded with the filesystem
2724 encoding. If *path* is ``None``, :func:`listxattr` will examine the current
2725 directory.
2726
2727 This function can support :ref:`specifying a file descriptor <path_fd>` and
2728 :ref:`not following symlinks <follow_symlinks>`.
2729
2730
2731.. function:: removexattr(path, attribute, *, follow_symlinks=True)
2732
2733 Removes the extended filesystem attribute *attribute* from *path*.
2734 *attribute* should be bytes or str. If it is a string, it is encoded
2735 with the filesystem encoding.
2736
2737 This function can support :ref:`specifying a file descriptor <path_fd>` and
2738 :ref:`not following symlinks <follow_symlinks>`.
2739
2740
2741.. function:: setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)
2742
2743 Set the extended filesystem attribute *attribute* on *path* to *value*.
2744 *attribute* must be a bytes or str with no embedded NULs. If it is a str,
2745 it is encoded with the filesystem encoding. *flags* may be
2746 :data:`XATTR_REPLACE` or :data:`XATTR_CREATE`. If :data:`XATTR_REPLACE` is
2747 given and the attribute does not exist, ``EEXISTS`` will be raised.
2748 If :data:`XATTR_CREATE` is given and the attribute already exists, the
2749 attribute will not be created and ``ENODATA`` will be raised.
2750
2751 This function can support :ref:`specifying a file descriptor <path_fd>` and
2752 :ref:`not following symlinks <follow_symlinks>`.
2753
2754 .. note::
2755
2756 A bug in Linux kernel versions less than 2.6.39 caused the flags argument
2757 to be ignored on some filesystems.
2758
2759
2760.. data:: XATTR_SIZE_MAX
2761
2762 The maximum size the value of an extended attribute can be. Currently, this
Serhiy Storchakaf8def282013-02-16 17:29:56 +02002763 is 64 KiB on Linux.
Georg Brandlb9831ab2012-06-24 11:57:07 +02002764
2765
2766.. data:: XATTR_CREATE
2767
2768 This is a possible value for the flags argument in :func:`setxattr`. It
2769 indicates the operation must create an attribute.
2770
2771
2772.. data:: XATTR_REPLACE
2773
2774 This is a possible value for the flags argument in :func:`setxattr`. It
2775 indicates the operation must replace an existing attribute.
2776
2777
Georg Brandl116aa622007-08-15 14:28:22 +00002778.. _os-process:
2779
2780Process Management
2781------------------
2782
2783These functions may be used to create and manage processes.
2784
Serhiy Storchakadab83542013-10-13 20:12:43 +03002785The various :func:`exec\* <execl>` functions take a list of arguments for the new
Georg Brandl116aa622007-08-15 14:28:22 +00002786program loaded into the process. In each case, the first of these arguments is
2787passed to the new program as its own name rather than as an argument a user may
2788have typed on a command line. For the C programmer, this is the ``argv[0]``
Georg Brandl60203b42010-10-06 10:11:56 +00002789passed to a program's :c:func:`main`. For example, ``os.execv('/bin/echo',
Georg Brandl116aa622007-08-15 14:28:22 +00002790['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
2791to be ignored.
2792
2793
2794.. function:: abort()
2795
2796 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
2797 behavior is to produce a core dump; on Windows, the process immediately returns
Victor Stinner6e2e3b92011-07-08 02:26:39 +02002798 an exit code of ``3``. Be aware that calling this function will not call the
2799 Python signal handler registered for :const:`SIGABRT` with
2800 :func:`signal.signal`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002801
Georg Brandlc575c902008-09-13 17:46:05 +00002802 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002803
2804
2805.. function:: execl(path, arg0, arg1, ...)
2806 execle(path, arg0, arg1, ..., env)
2807 execlp(file, arg0, arg1, ...)
2808 execlpe(file, arg0, arg1, ..., env)
2809 execv(path, args)
2810 execve(path, args, env)
2811 execvp(file, args)
2812 execvpe(file, args, env)
2813
2814 These functions all execute a new program, replacing the current process; they
2815 do not return. On Unix, the new executable is loaded into the current process,
Christian Heimesfaf2f632008-01-06 16:59:19 +00002816 and will have the same process id as the caller. Errors will be reported as
Georg Brandl48310cd2009-01-03 21:18:54 +00002817 :exc:`OSError` exceptions.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002818
2819 The current process is replaced immediately. Open file objects and
2820 descriptors are not flushed, so if there may be data buffered
2821 on these open files, you should flush them using
2822 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
Serhiy Storchakadab83542013-10-13 20:12:43 +03002823 :func:`exec\* <execl>` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002824
Serhiy Storchakadab83542013-10-13 20:12:43 +03002825 The "l" and "v" variants of the :func:`exec\* <execl>` functions differ in how
Christian Heimesfaf2f632008-01-06 16:59:19 +00002826 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00002827 to work with if the number of parameters is fixed when the code is written; the
2828 individual parameters simply become additional parameters to the :func:`execl\*`
Christian Heimesfaf2f632008-01-06 16:59:19 +00002829 functions. The "v" variants are good when the number of parameters is
Georg Brandl116aa622007-08-15 14:28:22 +00002830 variable, with the arguments being passed in a list or tuple as the *args*
2831 parameter. In either case, the arguments to the child process should start with
2832 the name of the command being run, but this is not enforced.
2833
Christian Heimesfaf2f632008-01-06 16:59:19 +00002834 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00002835 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
2836 :envvar:`PATH` environment variable to locate the program *file*. When the
Serhiy Storchakadab83542013-10-13 20:12:43 +03002837 environment is being replaced (using one of the :func:`exec\*e <execl>` variants,
Georg Brandl116aa622007-08-15 14:28:22 +00002838 discussed in the next paragraph), the new environment is used as the source of
2839 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
2840 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
2841 locate the executable; *path* must contain an appropriate absolute or relative
2842 path.
2843
2844 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Christian Heimesfaf2f632008-01-06 16:59:19 +00002845 that these all end in "e"), the *env* parameter must be a mapping which is
Christian Heimesa342c012008-04-20 21:01:16 +00002846 used to define the environment variables for the new process (these are used
2847 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl116aa622007-08-15 14:28:22 +00002848 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
Georg Brandl48310cd2009-01-03 21:18:54 +00002849 inherit the environment of the current process.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002850
Larry Hastings9cf065c2012-06-22 16:30:09 -07002851 For :func:`execve` on some platforms, *path* may also be specified as an open
2852 file descriptor. This functionality may not be supported on your platform;
2853 you can check whether or not it is available using :data:`os.supports_fd`.
2854 If it is unavailable, using it will raise a :exc:`NotImplementedError`.
2855
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002856 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002857
Larry Hastings9cf065c2012-06-22 16:30:09 -07002858 .. versionadded:: 3.3
2859 Added support for specifying an open file descriptor for *path*
2860 for :func:`execve`.
Georg Brandl116aa622007-08-15 14:28:22 +00002861
2862.. function:: _exit(n)
2863
Georg Brandl6f4e68d2010-10-17 10:51:45 +00002864 Exit the process with status *n*, without calling cleanup handlers, flushing
Benjamin Petersonf650e462010-05-06 23:03:05 +00002865 stdio buffers, etc.
2866
2867 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002868
2869 .. note::
2870
Georg Brandl6f4e68d2010-10-17 10:51:45 +00002871 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should
2872 normally only be used in the child process after a :func:`fork`.
Georg Brandl116aa622007-08-15 14:28:22 +00002873
Christian Heimesfaf2f632008-01-06 16:59:19 +00002874The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl116aa622007-08-15 14:28:22 +00002875although they are not required. These are typically used for system programs
2876written in Python, such as a mail server's external command delivery program.
2877
2878.. note::
2879
2880 Some of these may not be available on all Unix platforms, since there is some
2881 variation. These constants are defined where they are defined by the underlying
2882 platform.
2883
2884
2885.. data:: EX_OK
2886
Benjamin Petersonf650e462010-05-06 23:03:05 +00002887 Exit code that means no error occurred.
2888
2889 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002890
Georg Brandl116aa622007-08-15 14:28:22 +00002891
2892.. data:: EX_USAGE
2893
2894 Exit code that means the command was used incorrectly, such as when the wrong
Benjamin Petersonf650e462010-05-06 23:03:05 +00002895 number of arguments are given.
2896
2897 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002898
Georg Brandl116aa622007-08-15 14:28:22 +00002899
2900.. data:: EX_DATAERR
2901
Benjamin Petersonf650e462010-05-06 23:03:05 +00002902 Exit code that means the input data was incorrect.
2903
2904 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002905
Georg Brandl116aa622007-08-15 14:28:22 +00002906
2907.. data:: EX_NOINPUT
2908
2909 Exit code that means an input file did not exist or was not readable.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002910
Georg Brandlc575c902008-09-13 17:46:05 +00002911 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002912
Georg Brandl116aa622007-08-15 14:28:22 +00002913
2914.. data:: EX_NOUSER
2915
Benjamin Petersonf650e462010-05-06 23:03:05 +00002916 Exit code that means a specified user did not exist.
2917
2918 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002919
Georg Brandl116aa622007-08-15 14:28:22 +00002920
2921.. data:: EX_NOHOST
2922
Benjamin Petersonf650e462010-05-06 23:03:05 +00002923 Exit code that means a specified host did not exist.
2924
2925 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002926
Georg Brandl116aa622007-08-15 14:28:22 +00002927
2928.. data:: EX_UNAVAILABLE
2929
Benjamin Petersonf650e462010-05-06 23:03:05 +00002930 Exit code that means that a required service is unavailable.
2931
2932 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002933
Georg Brandl116aa622007-08-15 14:28:22 +00002934
2935.. data:: EX_SOFTWARE
2936
Benjamin Petersonf650e462010-05-06 23:03:05 +00002937 Exit code that means an internal software error was detected.
2938
2939 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002940
Georg Brandl116aa622007-08-15 14:28:22 +00002941
2942.. data:: EX_OSERR
2943
2944 Exit code that means an operating system error was detected, such as the
Benjamin Petersonf650e462010-05-06 23:03:05 +00002945 inability to fork or create a pipe.
2946
2947 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002948
Georg Brandl116aa622007-08-15 14:28:22 +00002949
2950.. data:: EX_OSFILE
2951
2952 Exit code that means some system file did not exist, could not be opened, or had
Benjamin Petersonf650e462010-05-06 23:03:05 +00002953 some other kind of error.
2954
2955 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002956
Georg Brandl116aa622007-08-15 14:28:22 +00002957
2958.. data:: EX_CANTCREAT
2959
2960 Exit code that means a user specified output file could not be created.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002961
Georg Brandlc575c902008-09-13 17:46:05 +00002962 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002963
Georg Brandl116aa622007-08-15 14:28:22 +00002964
2965.. data:: EX_IOERR
2966
2967 Exit code that means that an error occurred while doing I/O on some file.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002968
Georg Brandlc575c902008-09-13 17:46:05 +00002969 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002970
Georg Brandl116aa622007-08-15 14:28:22 +00002971
2972.. data:: EX_TEMPFAIL
2973
2974 Exit code that means a temporary failure occurred. This indicates something
2975 that may not really be an error, such as a network connection that couldn't be
Benjamin Petersonf650e462010-05-06 23:03:05 +00002976 made during a retryable operation.
2977
2978 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002979
Georg Brandl116aa622007-08-15 14:28:22 +00002980
2981.. data:: EX_PROTOCOL
2982
2983 Exit code that means that a protocol exchange was illegal, invalid, or not
Benjamin Petersonf650e462010-05-06 23:03:05 +00002984 understood.
2985
2986 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002987
Georg Brandl116aa622007-08-15 14:28:22 +00002988
2989.. data:: EX_NOPERM
2990
2991 Exit code that means that there were insufficient permissions to perform the
Benjamin Petersonf650e462010-05-06 23:03:05 +00002992 operation (but not intended for file system problems).
2993
2994 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002995
Georg Brandl116aa622007-08-15 14:28:22 +00002996
2997.. data:: EX_CONFIG
2998
2999 Exit code that means that some kind of configuration error occurred.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003000
Georg Brandlc575c902008-09-13 17:46:05 +00003001 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003002
Georg Brandl116aa622007-08-15 14:28:22 +00003003
3004.. data:: EX_NOTFOUND
3005
Benjamin Petersonf650e462010-05-06 23:03:05 +00003006 Exit code that means something like "an entry was not found".
3007
3008 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003009
Georg Brandl116aa622007-08-15 14:28:22 +00003010
3011.. function:: fork()
3012
Christian Heimesfaf2f632008-01-06 16:59:19 +00003013 Fork a child process. Return ``0`` in the child and the child's process id in the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003014 parent. If an error occurs :exc:`OSError` is raised.
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +00003015
Larry Hastings3732ed22014-03-15 21:13:56 -07003016 Note that some platforms including FreeBSD <= 6.3 and Cygwin have
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +00003017 known issues when using fork() from a thread.
3018
Christian Heimes3046fe42013-10-29 21:08:56 +01003019 .. warning::
3020
3021 See :mod:`ssl` for applications that use the SSL module with fork().
3022
Georg Brandlc575c902008-09-13 17:46:05 +00003023 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003024
3025
3026.. function:: forkpty()
3027
3028 Fork a child process, using a new pseudo-terminal as the child's controlling
3029 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
3030 new child's process id in the parent, and *fd* is the file descriptor of the
3031 master end of the pseudo-terminal. For a more portable approach, use the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003032 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003033
Georg Brandlc575c902008-09-13 17:46:05 +00003034 Availability: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003035
3036
3037.. function:: kill(pid, sig)
3038
3039 .. index::
3040 single: process; killing
3041 single: process; signalling
3042
3043 Send signal *sig* to the process *pid*. Constants for the specific signals
3044 available on the host platform are defined in the :mod:`signal` module.
Brian Curtineb24d742010-04-12 17:16:38 +00003045
3046 Windows: The :data:`signal.CTRL_C_EVENT` and
3047 :data:`signal.CTRL_BREAK_EVENT` signals are special signals which can
3048 only be sent to console processes which share a common console window,
3049 e.g., some subprocesses. Any other value for *sig* will cause the process
3050 to be unconditionally killed by the TerminateProcess API, and the exit code
3051 will be set to *sig*. The Windows version of :func:`kill` additionally takes
3052 process handles to be killed.
Georg Brandl116aa622007-08-15 14:28:22 +00003053
Victor Stinnerb3e72192011-05-08 01:46:11 +02003054 See also :func:`signal.pthread_kill`.
3055
Georg Brandl67b21b72010-08-17 15:07:14 +00003056 .. versionadded:: 3.2
3057 Windows support.
Brian Curtin904bd392010-04-20 15:28:06 +00003058
Georg Brandl116aa622007-08-15 14:28:22 +00003059
3060.. function:: killpg(pgid, sig)
3061
3062 .. index::
3063 single: process; killing
3064 single: process; signalling
3065
Benjamin Petersonf650e462010-05-06 23:03:05 +00003066 Send the signal *sig* to the process group *pgid*.
3067
3068 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003069
Georg Brandl116aa622007-08-15 14:28:22 +00003070
3071.. function:: nice(increment)
3072
3073 Add *increment* to the process's "niceness". Return the new niceness.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003074
Georg Brandlc575c902008-09-13 17:46:05 +00003075 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003076
3077
3078.. function:: plock(op)
3079
3080 Lock program segments into memory. The value of *op* (defined in
Benjamin Petersonf650e462010-05-06 23:03:05 +00003081 ``<sys/lock.h>``) determines which segments are locked.
3082
3083 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003084
3085
Andrew Kuchlingf5a42922014-04-16 09:10:53 -04003086.. function:: popen(command, mode='r', buffering=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00003087
Andrew Kuchlingf5a42922014-04-16 09:10:53 -04003088 Open a pipe to or from *command*. The return value is an open file object
3089 connected to the pipe, which can be read or written depending on whether *mode*
3090 is ``'r'`` (default) or ``'w'``. The *buffering* argument has the same meaning as
3091 the corresponding argument to the built-in :func:`open` function. The
3092 returned file object reads or writes text strings rather than bytes.
3093
3094 The ``close`` method returns :const:`None` if the subprocess exited
3095 successfully, or the subprocess's return code if there was an
3096 error. On POSIX systems, if the return code is positive it
3097 represents the return value of the process left-shifted by one
3098 byte. If the return code is negative, the process was terminated
3099 by the signal given by the negated value of the return code. (For
3100 example, the return value might be ``- signal.SIGKILL`` if the
3101 subprocess was killed.) On Windows systems, the return value
3102 contains the signed integer return code from the child process.
3103
3104 This is implemented using :class:`subprocess.Popen`; see that class's
3105 documentation for more powerful ways to manage and communicate with
3106 subprocesses.
Georg Brandl116aa622007-08-15 14:28:22 +00003107
3108
3109.. function:: spawnl(mode, path, ...)
3110 spawnle(mode, path, ..., env)
3111 spawnlp(mode, file, ...)
3112 spawnlpe(mode, file, ..., env)
3113 spawnv(mode, path, args)
3114 spawnve(mode, path, args, env)
3115 spawnvp(mode, file, args)
3116 spawnvpe(mode, file, args, env)
3117
3118 Execute the program *path* in a new process.
3119
3120 (Note that the :mod:`subprocess` module provides more powerful facilities for
3121 spawning new processes and retrieving their results; using that module is
Benjamin Peterson87c8d872009-06-11 22:54:11 +00003122 preferable to using these functions. Check especially the
3123 :ref:`subprocess-replacements` section.)
Georg Brandl116aa622007-08-15 14:28:22 +00003124
Christian Heimesfaf2f632008-01-06 16:59:19 +00003125 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl116aa622007-08-15 14:28:22 +00003126 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
3127 exits normally, or ``-signal``, where *signal* is the signal that killed the
Christian Heimesfaf2f632008-01-06 16:59:19 +00003128 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl116aa622007-08-15 14:28:22 +00003129 be used with the :func:`waitpid` function.
3130
Serhiy Storchakadab83542013-10-13 20:12:43 +03003131 The "l" and "v" variants of the :func:`spawn\* <spawnl>` functions differ in how
Christian Heimesfaf2f632008-01-06 16:59:19 +00003132 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00003133 to work with if the number of parameters is fixed when the code is written; the
3134 individual parameters simply become additional parameters to the
Christian Heimesfaf2f632008-01-06 16:59:19 +00003135 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl116aa622007-08-15 14:28:22 +00003136 parameters is variable, with the arguments being passed in a list or tuple as
3137 the *args* parameter. In either case, the arguments to the child process must
3138 start with the name of the command being run.
3139
Christian Heimesfaf2f632008-01-06 16:59:19 +00003140 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00003141 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
3142 :envvar:`PATH` environment variable to locate the program *file*. When the
Serhiy Storchakadab83542013-10-13 20:12:43 +03003143 environment is being replaced (using one of the :func:`spawn\*e <spawnl>` variants,
Georg Brandl116aa622007-08-15 14:28:22 +00003144 discussed in the next paragraph), the new environment is used as the source of
3145 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
3146 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
3147 :envvar:`PATH` variable to locate the executable; *path* must contain an
3148 appropriate absolute or relative path.
3149
3150 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Christian Heimesfaf2f632008-01-06 16:59:19 +00003151 (note that these all end in "e"), the *env* parameter must be a mapping
Christian Heimesa342c012008-04-20 21:01:16 +00003152 which is used to define the environment variables for the new process (they are
3153 used instead of the current process' environment); the functions
Georg Brandl116aa622007-08-15 14:28:22 +00003154 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
Benjamin Petersond23f8222009-04-05 19:13:16 +00003155 the new process to inherit the environment of the current process. Note that
3156 keys and values in the *env* dictionary must be strings; invalid keys or
3157 values will cause the function to fail, with a return value of ``127``.
Georg Brandl116aa622007-08-15 14:28:22 +00003158
3159 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
3160 equivalent::
3161
3162 import os
3163 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
3164
3165 L = ['cp', 'index.html', '/dev/null']
3166 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
3167
3168 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
Antoine Pitrou0e752dd2011-07-19 01:26:58 +02003169 and :func:`spawnvpe` are not available on Windows. :func:`spawnle` and
3170 :func:`spawnve` are not thread-safe on Windows; we advise you to use the
3171 :mod:`subprocess` module instead.
Georg Brandl116aa622007-08-15 14:28:22 +00003172
Georg Brandl116aa622007-08-15 14:28:22 +00003173
3174.. data:: P_NOWAIT
3175 P_NOWAITO
3176
Serhiy Storchakadab83542013-10-13 20:12:43 +03003177 Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
Georg Brandl116aa622007-08-15 14:28:22 +00003178 functions. If either of these values is given, the :func:`spawn\*` functions
Christian Heimesfaf2f632008-01-06 16:59:19 +00003179 will return as soon as the new process has been created, with the process id as
Benjamin Petersonf650e462010-05-06 23:03:05 +00003180 the return value.
3181
3182 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00003183
Georg Brandl116aa622007-08-15 14:28:22 +00003184
3185.. data:: P_WAIT
3186
Serhiy Storchakadab83542013-10-13 20:12:43 +03003187 Possible value for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
Georg Brandl116aa622007-08-15 14:28:22 +00003188 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
3189 return until the new process has run to completion and will return the exit code
3190 of the process the run is successful, or ``-signal`` if a signal kills the
Benjamin Petersonf650e462010-05-06 23:03:05 +00003191 process.
3192
3193 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00003194
Georg Brandl116aa622007-08-15 14:28:22 +00003195
3196.. data:: P_DETACH
3197 P_OVERLAY
3198
Serhiy Storchakadab83542013-10-13 20:12:43 +03003199 Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
Georg Brandl116aa622007-08-15 14:28:22 +00003200 functions. These are less portable than those listed above. :const:`P_DETACH`
3201 is similar to :const:`P_NOWAIT`, but the new process is detached from the
3202 console of the calling process. If :const:`P_OVERLAY` is used, the current
Serhiy Storchakadab83542013-10-13 20:12:43 +03003203 process will be replaced; the :func:`spawn\* <spawnl>` function will not return.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003204
Georg Brandl116aa622007-08-15 14:28:22 +00003205 Availability: Windows.
3206
Georg Brandl116aa622007-08-15 14:28:22 +00003207
3208.. function:: startfile(path[, operation])
3209
3210 Start a file with its associated application.
3211
3212 When *operation* is not specified or ``'open'``, this acts like double-clicking
3213 the file in Windows Explorer, or giving the file name as an argument to the
3214 :program:`start` command from the interactive command shell: the file is opened
3215 with whatever application (if any) its extension is associated.
3216
3217 When another *operation* is given, it must be a "command verb" that specifies
3218 what should be done with the file. Common verbs documented by Microsoft are
3219 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
3220 ``'find'`` (to be used on directories).
3221
3222 :func:`startfile` returns as soon as the associated application is launched.
3223 There is no option to wait for the application to close, and no way to retrieve
3224 the application's exit status. The *path* parameter is relative to the current
3225 directory. If you want to use an absolute path, make sure the first character
Georg Brandl60203b42010-10-06 10:11:56 +00003226 is not a slash (``'/'``); the underlying Win32 :c:func:`ShellExecute` function
Georg Brandl116aa622007-08-15 14:28:22 +00003227 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
Benjamin Petersonf650e462010-05-06 23:03:05 +00003228 the path is properly encoded for Win32.
3229
Steve Dower7d0e0c92015-01-24 08:18:24 -08003230 To reduce interpreter startup overhead, the Win32 :c:func:`ShellExecute`
3231 function is not resolved until this function is first called. If the function
3232 cannot be resolved, :exc:`NotImplementedError` will be raised.
3233
Benjamin Petersonf650e462010-05-06 23:03:05 +00003234 Availability: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00003235
Georg Brandl116aa622007-08-15 14:28:22 +00003236
3237.. function:: system(command)
3238
3239 Execute the command (a string) in a subshell. This is implemented by calling
Georg Brandl60203b42010-10-06 10:11:56 +00003240 the Standard C function :c:func:`system`, and has the same limitations.
Georg Brandl8f7b4272010-10-14 06:35:53 +00003241 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of
3242 the executed command. If *command* generates any output, it will be sent to
3243 the interpreter standard output stream.
Georg Brandl116aa622007-08-15 14:28:22 +00003244
3245 On Unix, the return value is the exit status of the process encoded in the
Georg Brandl8f7b4272010-10-14 06:35:53 +00003246 format specified for :func:`wait`. Note that POSIX does not specify the
3247 meaning of the return value of the C :c:func:`system` function, so the return
3248 value of the Python function is system-dependent.
Georg Brandl116aa622007-08-15 14:28:22 +00003249
Georg Brandl8f7b4272010-10-14 06:35:53 +00003250 On Windows, the return value is that returned by the system shell after
3251 running *command*. The shell is given by the Windows environment variable
3252 :envvar:`COMSPEC`: it is usually :program:`cmd.exe`, which returns the exit
3253 status of the command run; on systems using a non-native shell, consult your
3254 shell documentation.
Georg Brandl116aa622007-08-15 14:28:22 +00003255
Georg Brandl8f7b4272010-10-14 06:35:53 +00003256 The :mod:`subprocess` module provides more powerful facilities for spawning
3257 new processes and retrieving their results; using that module is preferable
3258 to using this function. See the :ref:`subprocess-replacements` section in
3259 the :mod:`subprocess` documentation for some helpful recipes.
Georg Brandl116aa622007-08-15 14:28:22 +00003260
Benjamin Petersonf650e462010-05-06 23:03:05 +00003261 Availability: Unix, Windows.
3262
Georg Brandl116aa622007-08-15 14:28:22 +00003263
3264.. function:: times()
3265
Larry Hastings605a62d2012-06-24 04:33:36 -07003266 Returns the current global process times.
3267 The return value is an object with five attributes:
3268
3269 * :attr:`user` - user time
3270 * :attr:`system` - system time
3271 * :attr:`children_user` - user time of all child processes
3272 * :attr:`children_system` - system time of all child processes
3273 * :attr:`elapsed` - elapsed real time since a fixed point in the past
3274
3275 For backwards compatibility, this object also behaves like a five-tuple
3276 containing :attr:`user`, :attr:`system`, :attr:`children_user`,
3277 :attr:`children_system`, and :attr:`elapsed` in that order.
3278
3279 See the Unix manual page
Benjamin Petersonf650e462010-05-06 23:03:05 +00003280 :manpage:`times(2)` or the corresponding Windows Platform API documentation.
Larry Hastings605a62d2012-06-24 04:33:36 -07003281 On Windows, only :attr:`user` and :attr:`system` are known; the other
3282 attributes are zero.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003283
Georg Brandl8a5555f2012-06-24 13:29:09 +02003284 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00003285
Larry Hastings605a62d2012-06-24 04:33:36 -07003286 .. versionchanged:: 3.3
3287 Return type changed from a tuple to a tuple-like object
3288 with named attributes.
3289
Georg Brandl116aa622007-08-15 14:28:22 +00003290
3291.. function:: wait()
3292
3293 Wait for completion of a child process, and return a tuple containing its pid
3294 and exit status indication: a 16-bit number, whose low byte is the signal number
3295 that killed the process, and whose high byte is the exit status (if the signal
3296 number is zero); the high bit of the low byte is set if a core file was
Benjamin Petersonf650e462010-05-06 23:03:05 +00003297 produced.
3298
3299 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003300
Ross Lagerwall7807c352011-03-17 20:20:30 +02003301.. function:: waitid(idtype, id, options)
3302
3303 Wait for the completion of one or more child processes.
3304 *idtype* can be :data:`P_PID`, :data:`P_PGID` or :data:`P_ALL`.
3305 *id* specifies the pid to wait on.
3306 *options* is constructed from the ORing of one or more of :data:`WEXITED`,
3307 :data:`WSTOPPED` or :data:`WCONTINUED` and additionally may be ORed with
3308 :data:`WNOHANG` or :data:`WNOWAIT`. The return value is an object
3309 representing the data contained in the :c:type:`siginfo_t` structure, namely:
3310 :attr:`si_pid`, :attr:`si_uid`, :attr:`si_signo`, :attr:`si_status`,
3311 :attr:`si_code` or ``None`` if :data:`WNOHANG` is specified and there are no
3312 children in a waitable state.
3313
3314 Availability: Unix.
3315
3316 .. versionadded:: 3.3
3317
3318.. data:: P_PID
3319 P_PGID
3320 P_ALL
3321
3322 These are the possible values for *idtype* in :func:`waitid`. They affect
3323 how *id* is interpreted.
3324
3325 Availability: Unix.
3326
3327 .. versionadded:: 3.3
3328
3329.. data:: WEXITED
3330 WSTOPPED
3331 WNOWAIT
3332
3333 Flags that can be used in *options* in :func:`waitid` that specify what
3334 child signal to wait for.
3335
3336 Availability: Unix.
3337
3338 .. versionadded:: 3.3
3339
3340
3341.. data:: CLD_EXITED
3342 CLD_DUMPED
3343 CLD_TRAPPED
3344 CLD_CONTINUED
3345
3346 These are the possible values for :attr:`si_code` in the result returned by
3347 :func:`waitid`.
3348
3349 Availability: Unix.
3350
3351 .. versionadded:: 3.3
3352
Georg Brandl116aa622007-08-15 14:28:22 +00003353
3354.. function:: waitpid(pid, options)
3355
3356 The details of this function differ on Unix and Windows.
3357
3358 On Unix: Wait for completion of a child process given by process id *pid*, and
3359 return a tuple containing its process id and exit status indication (encoded as
3360 for :func:`wait`). The semantics of the call are affected by the value of the
3361 integer *options*, which should be ``0`` for normal operation.
3362
3363 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
3364 that specific process. If *pid* is ``0``, the request is for the status of any
3365 child in the process group of the current process. If *pid* is ``-1``, the
3366 request pertains to any child of the current process. If *pid* is less than
3367 ``-1``, status is requested for any process in the process group ``-pid`` (the
3368 absolute value of *pid*).
3369
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00003370 An :exc:`OSError` is raised with the value of errno when the syscall
3371 returns -1.
3372
Georg Brandl116aa622007-08-15 14:28:22 +00003373 On Windows: Wait for completion of a process given by process handle *pid*, and
3374 return a tuple containing *pid*, and its exit status shifted left by 8 bits
3375 (shifting makes cross-platform use of the function easier). A *pid* less than or
3376 equal to ``0`` has no special meaning on Windows, and raises an exception. The
3377 value of integer *options* has no effect. *pid* can refer to any process whose
Serhiy Storchakadab83542013-10-13 20:12:43 +03003378 id is known, not necessarily a child process. The :func:`spawn\* <spawnl>`
3379 functions called with :const:`P_NOWAIT` return suitable process handles.
Georg Brandl116aa622007-08-15 14:28:22 +00003380
Victor Stinnera766ddf2015-03-26 23:50:57 +01003381 .. versionchanged:: 3.5
Victor Stinner708d9ba2015-04-02 11:49:42 +02003382 If the system call is interrupted and the signal handler does not raise an
Victor Stinnera766ddf2015-03-26 23:50:57 +01003383 exception, the function now retries the system call instead of raising an
3384 :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
3385
Georg Brandl116aa622007-08-15 14:28:22 +00003386
Ezio Melottiba4d8ed2012-11-23 19:45:52 +02003387.. function:: wait3(options)
Georg Brandl116aa622007-08-15 14:28:22 +00003388
3389 Similar to :func:`waitpid`, except no process id argument is given and a
3390 3-element tuple containing the child's process id, exit status indication, and
3391 resource usage information is returned. Refer to :mod:`resource`.\
Serhiy Storchakadab83542013-10-13 20:12:43 +03003392 :func:`~resource.getrusage` for details on resource usage information. The
3393 option argument is the same as that provided to :func:`waitpid` and
3394 :func:`wait4`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003395
Georg Brandl116aa622007-08-15 14:28:22 +00003396 Availability: Unix.
3397
Georg Brandl116aa622007-08-15 14:28:22 +00003398
Victor Stinner4195b5c2012-02-08 23:03:19 +01003399.. function:: wait4(pid, options)
Georg Brandl116aa622007-08-15 14:28:22 +00003400
3401 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
3402 process id, exit status indication, and resource usage information is returned.
Serhiy Storchakadab83542013-10-13 20:12:43 +03003403 Refer to :mod:`resource`.\ :func:`~resource.getrusage` for details on
3404 resource usage information. The arguments to :func:`wait4` are the same
3405 as those provided to :func:`waitpid`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003406
3407 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003408
Georg Brandl116aa622007-08-15 14:28:22 +00003409
3410.. data:: WNOHANG
3411
3412 The option for :func:`waitpid` to return immediately if no child process status
3413 is available immediately. The function returns ``(0, 0)`` in this case.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003414
Georg Brandlc575c902008-09-13 17:46:05 +00003415 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003416
3417
3418.. data:: WCONTINUED
3419
3420 This option causes child processes to be reported if they have been continued
Benjamin Petersonf650e462010-05-06 23:03:05 +00003421 from a job control stop since their status was last reported.
3422
Georg Brandl8a5555f2012-06-24 13:29:09 +02003423 Availability: some Unix systems.
Georg Brandl116aa622007-08-15 14:28:22 +00003424
Georg Brandl116aa622007-08-15 14:28:22 +00003425
3426.. data:: WUNTRACED
3427
3428 This option causes child processes to be reported if they have been stopped but
Benjamin Petersonf650e462010-05-06 23:03:05 +00003429 their current state has not been reported since they were stopped.
3430
3431 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003432
Georg Brandl116aa622007-08-15 14:28:22 +00003433
3434The following functions take a process status code as returned by
3435:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
3436used to determine the disposition of a process.
3437
Georg Brandl116aa622007-08-15 14:28:22 +00003438.. function:: WCOREDUMP(status)
3439
Christian Heimesfaf2f632008-01-06 16:59:19 +00003440 Return ``True`` if a core dump was generated for the process, otherwise
Benjamin Petersonf650e462010-05-06 23:03:05 +00003441 return ``False``.
3442
3443 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003444
Georg Brandl116aa622007-08-15 14:28:22 +00003445
3446.. function:: WIFCONTINUED(status)
3447
Christian Heimesfaf2f632008-01-06 16:59:19 +00003448 Return ``True`` if the process has been continued from a job control stop,
Benjamin Petersonf650e462010-05-06 23:03:05 +00003449 otherwise return ``False``.
3450
3451 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003452
Georg Brandl116aa622007-08-15 14:28:22 +00003453
3454.. function:: WIFSTOPPED(status)
3455
Christian Heimesfaf2f632008-01-06 16:59:19 +00003456 Return ``True`` if the process has been stopped, otherwise return
Benjamin Petersonf650e462010-05-06 23:03:05 +00003457 ``False``.
3458
3459 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003460
3461
3462.. function:: WIFSIGNALED(status)
3463
Christian Heimesfaf2f632008-01-06 16:59:19 +00003464 Return ``True`` if the process exited due to a signal, otherwise return
Benjamin Petersonf650e462010-05-06 23:03:05 +00003465 ``False``.
3466
3467 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003468
3469
3470.. function:: WIFEXITED(status)
3471
Christian Heimesfaf2f632008-01-06 16:59:19 +00003472 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
Benjamin Petersonf650e462010-05-06 23:03:05 +00003473 otherwise return ``False``.
3474
3475 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003476
3477
3478.. function:: WEXITSTATUS(status)
3479
3480 If ``WIFEXITED(status)`` is true, return the integer parameter to the
3481 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003482
Georg Brandlc575c902008-09-13 17:46:05 +00003483 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003484
3485
3486.. function:: WSTOPSIG(status)
3487
Benjamin Petersonf650e462010-05-06 23:03:05 +00003488 Return the signal which caused the process to stop.
3489
3490 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003491
3492
3493.. function:: WTERMSIG(status)
3494
Benjamin Petersonf650e462010-05-06 23:03:05 +00003495 Return the signal which caused the process to exit.
3496
3497 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003498
3499
Benjamin Peterson94b580d2011-08-02 17:30:04 -05003500Interface to the scheduler
3501--------------------------
3502
3503These functions control how a process is allocated CPU time by the operating
3504system. They are only available on some Unix platforms. For more detailed
3505information, consult your Unix manpages.
3506
3507.. versionadded:: 3.3
3508
Andrew Kuchling4921a082013-06-21 11:49:57 -04003509The following scheduling policies are exposed if they are supported by the
Benjamin Peterson94b580d2011-08-02 17:30:04 -05003510operating system.
3511
3512.. data:: SCHED_OTHER
3513
3514 The default scheduling policy.
3515
3516.. data:: SCHED_BATCH
3517
3518 Scheduling policy for CPU-intensive processes that tries to preserve
3519 interactivity on the rest of the computer.
3520
3521.. data:: SCHED_IDLE
3522
3523 Scheduling policy for extremely low priority background tasks.
3524
3525.. data:: SCHED_SPORADIC
3526
3527 Scheduling policy for sporadic server programs.
3528
3529.. data:: SCHED_FIFO
3530
3531 A First In First Out scheduling policy.
3532
3533.. data:: SCHED_RR
3534
3535 A round-robin scheduling policy.
3536
3537.. data:: SCHED_RESET_ON_FORK
3538
3539 This flag can OR'ed with any other scheduling policy. When a process with
3540 this flag set forks, its child's scheduling policy and priority are reset to
3541 the default.
3542
3543
3544.. class:: sched_param(sched_priority)
3545
3546 This class represents tunable scheduling parameters used in
3547 :func:`sched_setparam`, :func:`sched_setscheduler`, and
3548 :func:`sched_getparam`. It is immutable.
3549
3550 At the moment, there is only one possible parameter:
3551
3552 .. attribute:: sched_priority
3553
3554 The scheduling priority for a scheduling policy.
3555
3556
3557.. function:: sched_get_priority_min(policy)
3558
3559 Get the minimum priority value for *policy*. *policy* is one of the
3560 scheduling policy constants above.
3561
3562
3563.. function:: sched_get_priority_max(policy)
3564
3565 Get the maximum priority value for *policy*. *policy* is one of the
3566 scheduling policy constants above.
3567
3568
3569.. function:: sched_setscheduler(pid, policy, param)
3570
3571 Set the scheduling policy for the process with PID *pid*. A *pid* of 0 means
3572 the calling process. *policy* is one of the scheduling policy constants
3573 above. *param* is a :class:`sched_param` instance.
3574
3575
3576.. function:: sched_getscheduler(pid)
3577
3578 Return the scheduling policy for the process with PID *pid*. A *pid* of 0
3579 means the calling process. The result is one of the scheduling policy
3580 constants above.
3581
3582
3583.. function:: sched_setparam(pid, param)
3584
3585 Set a scheduling parameters for the process with PID *pid*. A *pid* of 0 means
3586 the calling process. *param* is a :class:`sched_param` instance.
3587
3588
3589.. function:: sched_getparam(pid)
3590
3591 Return the scheduling parameters as a :class:`sched_param` instance for the
3592 process with PID *pid*. A *pid* of 0 means the calling process.
3593
3594
3595.. function:: sched_rr_get_interval(pid)
3596
3597 Return the round-robin quantum in seconds for the process with PID *pid*. A
3598 *pid* of 0 means the calling process.
3599
3600
3601.. function:: sched_yield()
3602
3603 Voluntarily relinquish the CPU.
3604
3605
Benjamin Peterson94b580d2011-08-02 17:30:04 -05003606.. function:: sched_setaffinity(pid, mask)
3607
Antoine Pitrou84869872012-08-04 16:16:35 +02003608 Restrict the process with PID *pid* (or the current process if zero) to a
3609 set of CPUs. *mask* is an iterable of integers representing the set of
3610 CPUs to which the process should be restricted.
Benjamin Peterson94b580d2011-08-02 17:30:04 -05003611
3612
Antoine Pitrou84869872012-08-04 16:16:35 +02003613.. function:: sched_getaffinity(pid)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05003614
Antoine Pitrou84869872012-08-04 16:16:35 +02003615 Return the set of CPUs the process with PID *pid* (or the current process
3616 if zero) is restricted to.
Benjamin Peterson94b580d2011-08-02 17:30:04 -05003617
3618
Georg Brandl116aa622007-08-15 14:28:22 +00003619.. _os-path:
3620
3621Miscellaneous System Information
3622--------------------------------
3623
3624
3625.. function:: confstr(name)
3626
3627 Return string-valued system configuration values. *name* specifies the
3628 configuration value to retrieve; it may be a string which is the name of a
3629 defined system value; these names are specified in a number of standards (POSIX,
3630 Unix 95, Unix 98, and others). Some platforms define additional names as well.
3631 The names known to the host operating system are given as the keys of the
3632 ``confstr_names`` dictionary. For configuration variables not included in that
Benjamin Petersonf650e462010-05-06 23:03:05 +00003633 mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00003634
3635 If the configuration value specified by *name* isn't defined, ``None`` is
3636 returned.
3637
3638 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
3639 specific value for *name* is not supported by the host system, even if it is
3640 included in ``confstr_names``, an :exc:`OSError` is raised with
3641 :const:`errno.EINVAL` for the error number.
3642
Georg Brandl8a5555f2012-06-24 13:29:09 +02003643 Availability: Unix.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003644
Georg Brandl116aa622007-08-15 14:28:22 +00003645
3646.. data:: confstr_names
3647
3648 Dictionary mapping names accepted by :func:`confstr` to the integer values
3649 defined for those names by the host operating system. This can be used to
Benjamin Petersonf650e462010-05-06 23:03:05 +00003650 determine the set of names known to the system.
3651
3652 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003653
3654
Charles-Francois Natali44feda32013-05-20 14:40:46 +02003655.. function:: cpu_count()
3656
3657 Return the number of CPUs in the system. Returns None if undetermined.
3658
3659 .. versionadded:: 3.4
3660
3661
Georg Brandl116aa622007-08-15 14:28:22 +00003662.. function:: getloadavg()
3663
Christian Heimesa62da1d2008-01-12 19:39:10 +00003664 Return the number of processes in the system run queue averaged over the last
3665 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Benjamin Petersonf650e462010-05-06 23:03:05 +00003666 unobtainable.
3667
3668 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003669
Georg Brandl116aa622007-08-15 14:28:22 +00003670
3671.. function:: sysconf(name)
3672
3673 Return integer-valued system configuration values. If the configuration value
3674 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
3675 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
3676 provides information on the known names is given by ``sysconf_names``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003677
Georg Brandlc575c902008-09-13 17:46:05 +00003678 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003679
3680
3681.. data:: sysconf_names
3682
3683 Dictionary mapping names accepted by :func:`sysconf` to the integer values
3684 defined for those names by the host operating system. This can be used to
Benjamin Petersonf650e462010-05-06 23:03:05 +00003685 determine the set of names known to the system.
3686
3687 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003688
Christian Heimesfaf2f632008-01-06 16:59:19 +00003689The following data values are used to support path manipulation operations. These
Georg Brandl116aa622007-08-15 14:28:22 +00003690are defined for all platforms.
3691
3692Higher-level operations on pathnames are defined in the :mod:`os.path` module.
3693
3694
3695.. data:: curdir
3696
3697 The constant string used by the operating system to refer to the current
Georg Brandlc575c902008-09-13 17:46:05 +00003698 directory. This is ``'.'`` for Windows and POSIX. Also available via
3699 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00003700
3701
3702.. data:: pardir
3703
3704 The constant string used by the operating system to refer to the parent
Georg Brandlc575c902008-09-13 17:46:05 +00003705 directory. This is ``'..'`` for Windows and POSIX. Also available via
3706 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00003707
3708
3709.. data:: sep
3710
Georg Brandlc575c902008-09-13 17:46:05 +00003711 The character used by the operating system to separate pathname components.
3712 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
3713 is not sufficient to be able to parse or concatenate pathnames --- use
Georg Brandl116aa622007-08-15 14:28:22 +00003714 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
3715 useful. Also available via :mod:`os.path`.
3716
3717
3718.. data:: altsep
3719
3720 An alternative character used by the operating system to separate pathname
3721 components, or ``None`` if only one separator character exists. This is set to
3722 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
3723 :mod:`os.path`.
3724
3725
3726.. data:: extsep
3727
3728 The character which separates the base filename from the extension; for example,
3729 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
3730
Georg Brandl116aa622007-08-15 14:28:22 +00003731
3732.. data:: pathsep
3733
3734 The character conventionally used by the operating system to separate search
3735 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
3736 Windows. Also available via :mod:`os.path`.
3737
3738
3739.. data:: defpath
3740
Serhiy Storchakadab83542013-10-13 20:12:43 +03003741 The default search path used by :func:`exec\*p\* <execl>` and
3742 :func:`spawn\*p\* <spawnl>` if the environment doesn't have a ``'PATH'``
3743 key. Also available via :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00003744
3745
3746.. data:: linesep
3747
3748 The string used to separate (or, rather, terminate) lines on the current
Georg Brandlc575c902008-09-13 17:46:05 +00003749 platform. This may be a single character, such as ``'\n'`` for POSIX, or
3750 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
3751 *os.linesep* as a line terminator when writing files opened in text mode (the
3752 default); use a single ``'\n'`` instead, on all platforms.
Georg Brandl116aa622007-08-15 14:28:22 +00003753
3754
3755.. data:: devnull
3756
Georg Brandl850a9902010-05-21 22:04:32 +00003757 The file path of the null device. For example: ``'/dev/null'`` for
3758 POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00003759
Andrew Kuchling4921a082013-06-21 11:49:57 -04003760.. data:: RTLD_LAZY
3761 RTLD_NOW
3762 RTLD_GLOBAL
3763 RTLD_LOCAL
3764 RTLD_NODELETE
3765 RTLD_NOLOAD
3766 RTLD_DEEPBIND
3767
3768 Flags for use with the :func:`~sys.setdlopenflags` and
3769 :func:`~sys.getdlopenflags` functions. See the Unix manual page
3770 :manpage:`dlopen(3)` for what the different flags mean.
3771
3772 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +00003773
3774.. _os-miscfunc:
3775
3776Miscellaneous Functions
3777-----------------------
3778
3779
3780.. function:: urandom(n)
3781
3782 Return a string of *n* random bytes suitable for cryptographic use.
3783
3784 This function returns random bytes from an OS-specific randomness source. The
3785 returned data should be unpredictable enough for cryptographic applications,
Georg Brandlf62445a2012-06-24 13:31:20 +02003786 though its exact quality depends on the OS implementation. On a Unix-like
Georg Brandlc6a2c9b2013-10-06 18:43:19 +02003787 system this will query ``/dev/urandom``, and on Windows it will use
3788 ``CryptGenRandom()``. If a randomness source is not found,
3789 :exc:`NotImplementedError` will be raised.
Andrew Svetlov03cb99c2012-10-16 13:15:06 +03003790
Andrew Svetlov2bfe3862012-10-16 13:52:25 +03003791 For an easy-to-use interface to the random number generator
3792 provided by your platform, please see :class:`random.SystemRandom`.