blob: f417c34929fa7282364993ff4d0b3a6aefab0179 [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
56 names have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``,
57 ``'os2'``, ``'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:
68
69File Names, Command Line Arguments, and Environment Variables
70-------------------------------------------------------------
71
Georg Brandl67b21b72010-08-17 15:07:14 +000072In Python, file names, command line arguments, and environment variables are
73represented using the string type. On some systems, decoding these strings to
74and from bytes is necessary before passing them to the operating system. Python
75uses the file system encoding to perform this conversion (see
76:func:`sys.getfilesystemencoding`).
Martin v. Löwis011e8422009-05-05 04:43:17 +000077
78.. versionchanged:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +000079 On some systems, conversion using the file system encoding may fail. In this
80 case, Python uses the ``surrogateescape`` encoding error handler, which means
81 that undecodable bytes are replaced by a Unicode character U+DCxx on
82 decoding, and these are again translated to the original byte on encoding.
Martin v. Löwis011e8422009-05-05 04:43:17 +000083
84
Georg Brandl67b21b72010-08-17 15:07:14 +000085The file system encoding must guarantee to successfully decode all bytes
86below 128. If the file system encoding fails to provide this guarantee, API
87functions may raise UnicodeErrors.
Martin v. Löwis011e8422009-05-05 04:43:17 +000088
89
Georg Brandl116aa622007-08-15 14:28:22 +000090.. _os-procinfo:
91
92Process Parameters
93------------------
94
95These functions and data items provide information and operate on the current
96process and user.
97
98
99.. data:: environ
100
101 A mapping object representing the string environment. For example,
102 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
103 and is equivalent to ``getenv("HOME")`` in C.
104
105 This mapping is captured the first time the :mod:`os` module is imported,
106 typically during Python startup as part of processing :file:`site.py`. Changes
107 to the environment made after this time are not reflected in ``os.environ``,
108 except for changes made by modifying ``os.environ`` directly.
109
110 If the platform supports the :func:`putenv` function, this mapping may be used
111 to modify the environment as well as query the environment. :func:`putenv` will
112 be called automatically when the mapping is modified.
113
Victor Stinner84ae1182010-05-06 22:05:07 +0000114 On Unix, keys and values use :func:`sys.getfilesystemencoding` and
115 ``'surrogateescape'`` error handler. Use :data:`environb` if you would like
116 to use a different encoding.
117
Georg Brandl116aa622007-08-15 14:28:22 +0000118 .. note::
119
120 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
121 to modify ``os.environ``.
122
123 .. note::
124
Georg Brandlc575c902008-09-13 17:46:05 +0000125 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
126 cause memory leaks. Refer to the system documentation for
Georg Brandl60203b42010-10-06 10:11:56 +0000127 :c:func:`putenv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129 If :func:`putenv` is not provided, a modified copy of this mapping may be
130 passed to the appropriate process-creation functions to cause child processes
131 to use a modified environment.
132
Georg Brandl9afde1c2007-11-01 20:32:30 +0000133 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl116aa622007-08-15 14:28:22 +0000134 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl9afde1c2007-11-01 20:32:30 +0000135 automatically when an item is deleted from ``os.environ``, and when
136 one of the :meth:`pop` or :meth:`clear` methods is called.
137
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Victor Stinner84ae1182010-05-06 22:05:07 +0000139.. data:: environb
140
141 Bytes version of :data:`environ`: a mapping object representing the
142 environment as byte strings. :data:`environ` and :data:`environb` are
143 synchronized (modify :data:`environb` updates :data:`environ`, and vice
144 versa).
145
Victor Stinnerb745a742010-05-18 17:17:23 +0000146 :data:`environb` is only available if :data:`supports_bytes_environ` is
147 True.
Victor Stinner84ae1182010-05-06 22:05:07 +0000148
Benjamin Peterson662c74f2010-05-06 22:09:03 +0000149 .. versionadded:: 3.2
150
Victor Stinner84ae1182010-05-06 22:05:07 +0000151
Georg Brandl116aa622007-08-15 14:28:22 +0000152.. function:: chdir(path)
153 fchdir(fd)
154 getcwd()
155 :noindex:
156
157 These functions are described in :ref:`os-file-dir`.
158
159
Victor Stinnere8d51452010-08-19 01:05:19 +0000160.. function:: fsencode(filename)
Victor Stinner449c4662010-05-08 11:10:09 +0000161
Victor Stinnere8d51452010-08-19 01:05:19 +0000162 Encode *filename* to the filesystem encoding with ``'surrogateescape'``
Victor Stinner62165d62010-10-09 10:34:37 +0000163 error handler, or ``'strict'`` on Windows; return :class:`bytes` unchanged.
Victor Stinnere8d51452010-08-19 01:05:19 +0000164
Antoine Pitroua305ca72010-09-25 22:12:00 +0000165 :func:`fsdecode` is the reverse function.
Victor Stinnere8d51452010-08-19 01:05:19 +0000166
167 .. versionadded:: 3.2
168
169
170.. function:: fsdecode(filename)
171
172 Decode *filename* from the filesystem encoding with ``'surrogateescape'``
Victor Stinner62165d62010-10-09 10:34:37 +0000173 error handler, or ``'strict'`` on Windows; return :class:`str` unchanged.
Victor Stinnere8d51452010-08-19 01:05:19 +0000174
175 :func:`fsencode` is the reverse function.
Victor Stinner449c4662010-05-08 11:10:09 +0000176
177 .. versionadded:: 3.2
178
179
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000180.. function:: get_exec_path(env=None)
181
182 Returns the list of directories that will be searched for a named
183 executable, similar to a shell, when launching a process.
184 *env*, when specified, should be an environment variable dictionary
185 to lookup the PATH in.
186 By default, when *env* is None, :data:`environ` is used.
187
188 .. versionadded:: 3.2
189
190
Georg Brandl116aa622007-08-15 14:28:22 +0000191.. function:: ctermid()
192
193 Return the filename corresponding to the controlling terminal of the process.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000194
Georg Brandl116aa622007-08-15 14:28:22 +0000195 Availability: Unix.
196
197
198.. function:: getegid()
199
200 Return the effective group id of the current process. This corresponds to the
Benjamin Petersonf650e462010-05-06 23:03:05 +0000201 "set id" bit on the file being executed in the current process.
202
203 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000204
205
206.. function:: geteuid()
207
208 .. index:: single: user; effective id
209
Benjamin Petersonf650e462010-05-06 23:03:05 +0000210 Return the current process's effective user id.
211
212 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
215.. function:: getgid()
216
217 .. index:: single: process; group
218
Benjamin Petersonf650e462010-05-06 23:03:05 +0000219 Return the real group id of the current process.
220
221 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200224.. function:: getgrouplist(user, group)
225
226 Return list of group ids that *user* belongs to. If *group* is not in the
227 list, it is included; typically, *group* is specified as the group ID
228 field from the password record for *user*.
229
230 Availability: Unix.
231
232 .. versionadded:: 3.3
233
234
Georg Brandl116aa622007-08-15 14:28:22 +0000235.. function:: getgroups()
236
237 Return list of supplemental group ids associated with the current process.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000238
Georg Brandl116aa622007-08-15 14:28:22 +0000239 Availability: Unix.
240
Ned Deily2e209682012-04-30 11:14:02 -0700241 .. note:: On Mac OS X, :func:`getgroups` behavior differs somewhat from
242 other Unix platforms. If the Python interpreter was built with a
243 deployment target of :const:`10.5` or earlier, :func:`getgroups` returns
244 the list of effective group ids associated with the current user process;
245 this list is limited to a system-defined number of entries, typically 16,
246 and may be modified by calls to :func:`setgroups` if suitably privileged.
247 If built with a deployment target greater than :const:`10.5`,
248 :func:`getgroups` returns the current group access list for the user
249 associated with the effective user id of the process; the group access
250 list may change over the lifetime of the process, it is not affected by
251 calls to :func:`setgroups`, and its length is not limited to 16. The
252 deployment target value, :const:`MACOSX_DEPLOYMENT_TARGET`, can be
253 obtained with :func:`sysconfig.get_config_var`.
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Antoine Pitroub7572f02009-12-02 20:46:48 +0000256.. function:: initgroups(username, gid)
257
258 Call the system initgroups() to initialize the group access list with all of
259 the groups of which the specified username is a member, plus the specified
Benjamin Petersonf650e462010-05-06 23:03:05 +0000260 group id.
261
262 Availability: Unix.
Antoine Pitroub7572f02009-12-02 20:46:48 +0000263
264 .. versionadded:: 3.2
265
266
Georg Brandl116aa622007-08-15 14:28:22 +0000267.. function:: getlogin()
268
269 Return the name of the user logged in on the controlling terminal of the
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000270 process. For most purposes, it is more useful to use the environment variables
271 :envvar:`LOGNAME` or :envvar:`USERNAME` to find out who the user is, or
Georg Brandl116aa622007-08-15 14:28:22 +0000272 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
Benjamin Petersonf650e462010-05-06 23:03:05 +0000273 effective user id.
274
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000275 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277
278.. function:: getpgid(pid)
279
280 Return the process group id of the process with process id *pid*. If *pid* is 0,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000281 the process group id of the current process is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
Benjamin Petersonf650e462010-05-06 23:03:05 +0000283 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000284
285.. function:: getpgrp()
286
287 .. index:: single: process; group
288
Benjamin Petersonf650e462010-05-06 23:03:05 +0000289 Return the id of the current process group.
290
291 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293
294.. function:: getpid()
295
296 .. index:: single: process; id
297
Benjamin Petersonf650e462010-05-06 23:03:05 +0000298 Return the current process id.
299
300 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000301
302
303.. function:: getppid()
304
305 .. index:: single: process; id of parent
306
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000307 Return the parent's process id. When the parent process has exited, on Unix
308 the id returned is the one of the init process (1), on Windows it is still
309 the same id, which may be already reused by another process.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000310
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000311 Availability: Unix, Windows
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000313 .. versionchanged:: 3.2
314 Added support for Windows.
Georg Brandl1b83a452009-11-28 11:12:26 +0000315
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000316.. function:: getpriority(which, who)
317
318 .. index:: single: process; scheduling priority
319
320 Get program scheduling priority. The value *which* is one of
321 :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
322 is interpreted relative to *which* (a process identifier for
323 :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
324 user ID for :const:`PRIO_USER`). A zero value for *who* denotes
325 (respectively) the calling process, the process group of the calling process,
326 or the real user ID of the calling process.
327
328 Availability: Unix
329
330 .. versionadded:: 3.3
331
Gregory P. Smithcf02c6a2009-11-27 17:54:17 +0000332.. function:: getresuid()
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000333
334 Return a tuple (ruid, euid, suid) denoting the current process's
Benjamin Petersonf650e462010-05-06 23:03:05 +0000335 real, effective, and saved user ids.
336
337 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000338
Georg Brandl1b83a452009-11-28 11:12:26 +0000339 .. versionadded:: 3.2
340
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000341
Gregory P. Smithcf02c6a2009-11-27 17:54:17 +0000342.. function:: getresgid()
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000343
344 Return a tuple (rgid, egid, sgid) denoting the current process's
Georg Brandla9b51d22010-09-05 17:07:12 +0000345 real, effective, and saved group ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000346
347 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000348
Georg Brandl1b83a452009-11-28 11:12:26 +0000349 .. versionadded:: 3.2
350
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352.. function:: getuid()
353
354 .. index:: single: user; id
355
Benjamin Petersonf650e462010-05-06 23:03:05 +0000356 Return the current process's user id.
357
358 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360
Georg Brandl18244152009-09-02 20:34:52 +0000361.. function:: getenv(key, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Georg Brandl18244152009-09-02 20:34:52 +0000363 Return the value of the environment variable *key* if it exists, or
Victor Stinner84ae1182010-05-06 22:05:07 +0000364 *default* if it doesn't. *key*, *default* and the result are str.
Victor Stinner84ae1182010-05-06 22:05:07 +0000365
366 On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding`
367 and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you
368 would like to use a different encoding.
369
Benjamin Petersonf650e462010-05-06 23:03:05 +0000370 Availability: most flavors of Unix, Windows.
371
Victor Stinner84ae1182010-05-06 22:05:07 +0000372
373.. function:: getenvb(key, default=None)
374
375 Return the value of the environment variable *key* if it exists, or
376 *default* if it doesn't. *key*, *default* and the result are bytes.
Benjamin Peterson0d6fe512010-05-06 22:13:11 +0000377
Victor Stinner84ae1182010-05-06 22:05:07 +0000378 Availability: most flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000379
Benjamin Peterson0d6fe512010-05-06 22:13:11 +0000380 .. versionadded:: 3.2
381
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000382.. data:: PRIO_PROCESS
383 PRIO_PGRP
384 PRIO_USER
385
386 Parameters for :func:`getpriority` and :func:`setpriority` functions.
387
388 Availability: Unix.
389
390 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Georg Brandl18244152009-09-02 20:34:52 +0000392.. function:: putenv(key, value)
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394 .. index:: single: environment variables; setting
395
Georg Brandl18244152009-09-02 20:34:52 +0000396 Set the environment variable named *key* to the string *value*. Such
Georg Brandl116aa622007-08-15 14:28:22 +0000397 changes to the environment affect subprocesses started with :func:`os.system`,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000398 :func:`popen` or :func:`fork` and :func:`execv`.
399
400 Availability: most flavors of Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402 .. note::
403
Georg Brandlc575c902008-09-13 17:46:05 +0000404 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
405 cause memory leaks. Refer to the system documentation for putenv.
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
408 automatically translated into corresponding calls to :func:`putenv`; however,
409 calls to :func:`putenv` don't update ``os.environ``, so it is actually
410 preferable to assign to items of ``os.environ``.
411
412
413.. function:: setegid(egid)
414
Benjamin Petersonf650e462010-05-06 23:03:05 +0000415 Set the current process's effective group id.
416
417 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000418
419
420.. function:: seteuid(euid)
421
Benjamin Petersonf650e462010-05-06 23:03:05 +0000422 Set the current process's effective user id.
423
424 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426
427.. function:: setgid(gid)
428
Benjamin Petersonf650e462010-05-06 23:03:05 +0000429 Set the current process' group id.
430
431 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433
434.. function:: setgroups(groups)
435
436 Set the list of supplemental group ids associated with the current process to
437 *groups*. *groups* must be a sequence, and each element must be an integer
Christian Heimesfaf2f632008-01-06 16:59:19 +0000438 identifying a group. This operation is typically available only to the superuser.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000439
Georg Brandl116aa622007-08-15 14:28:22 +0000440 Availability: Unix.
441
Ned Deily2e209682012-04-30 11:14:02 -0700442 .. note:: On Mac OS X, the length of *groups* may not exceed the
443 system-defined maximum number of effective group ids, typically 16.
444 See the documentation for :func:`getgroups` for cases where it may not
445 return the same group list set by calling setgroups().
Georg Brandl116aa622007-08-15 14:28:22 +0000446
447.. function:: setpgrp()
448
Georg Brandl60203b42010-10-06 10:11:56 +0000449 Call the system call :c:func:`setpgrp` or :c:func:`setpgrp(0, 0)` depending on
Georg Brandl116aa622007-08-15 14:28:22 +0000450 which version is implemented (if any). See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000451
Georg Brandl116aa622007-08-15 14:28:22 +0000452 Availability: Unix.
453
454
455.. function:: setpgid(pid, pgrp)
456
Georg Brandl60203b42010-10-06 10:11:56 +0000457 Call the system call :c:func:`setpgid` to set the process group id of the
Georg Brandl116aa622007-08-15 14:28:22 +0000458 process with id *pid* to the process group with id *pgrp*. See the Unix manual
Benjamin Petersonf650e462010-05-06 23:03:05 +0000459 for the semantics.
460
461 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +0000464.. function:: setpriority(which, who, priority)
465
466 .. index:: single: process; scheduling priority
467
468 Set program scheduling priority. The value *which* is one of
469 :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
470 is interpreted relative to *which* (a process identifier for
471 :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
472 user ID for :const:`PRIO_USER`). A zero value for *who* denotes
473 (respectively) the calling process, the process group of the calling process,
474 or the real user ID of the calling process.
475 *priority* is a value in the range -20 to 19. The default priority is 0;
476 lower priorities cause more favorable scheduling.
477
478 Availability: Unix
479
480 .. versionadded:: 3.3
481
482
Georg Brandl116aa622007-08-15 14:28:22 +0000483.. function:: setregid(rgid, egid)
484
Benjamin Petersonf650e462010-05-06 23:03:05 +0000485 Set the current process's real and effective group ids.
486
487 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000488
Georg Brandl1b83a452009-11-28 11:12:26 +0000489
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000490.. function:: setresgid(rgid, egid, sgid)
491
492 Set the current process's real, effective, and saved group ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000493
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000494 Availability: Unix.
495
Georg Brandl1b83a452009-11-28 11:12:26 +0000496 .. versionadded:: 3.2
497
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000498
499.. function:: setresuid(ruid, euid, suid)
500
501 Set the current process's real, effective, and saved user ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000502
Georg Brandl6faee4e2010-09-21 14:48:28 +0000503 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000504
Georg Brandl1b83a452009-11-28 11:12:26 +0000505 .. versionadded:: 3.2
506
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000507
508.. function:: setreuid(ruid, euid)
509
Benjamin Petersonf650e462010-05-06 23:03:05 +0000510 Set the current process's real and effective user ids.
511
512 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000513
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515.. function:: getsid(pid)
516
Georg Brandl60203b42010-10-06 10:11:56 +0000517 Call the system call :c:func:`getsid`. See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000518
Georg Brandl116aa622007-08-15 14:28:22 +0000519 Availability: Unix.
520
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522.. function:: setsid()
523
Georg Brandl60203b42010-10-06 10:11:56 +0000524 Call the system call :c:func:`setsid`. See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000525
Georg Brandl116aa622007-08-15 14:28:22 +0000526 Availability: Unix.
527
528
529.. function:: setuid(uid)
530
531 .. index:: single: user; id, setting
532
Benjamin Petersonf650e462010-05-06 23:03:05 +0000533 Set the current process's user id.
534
535 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000536
Georg Brandl116aa622007-08-15 14:28:22 +0000537
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000538.. placed in this section since it relates to errno.... a little weak
Georg Brandl116aa622007-08-15 14:28:22 +0000539.. function:: strerror(code)
540
541 Return the error message corresponding to the error code in *code*.
Georg Brandl60203b42010-10-06 10:11:56 +0000542 On platforms where :c:func:`strerror` returns ``NULL`` when given an unknown
Benjamin Petersonf650e462010-05-06 23:03:05 +0000543 error number, :exc:`ValueError` is raised.
544
545 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547
Victor Stinnerb745a742010-05-18 17:17:23 +0000548.. data:: supports_bytes_environ
549
550 True if the native OS type of the environment is bytes (eg. False on
551 Windows).
552
Victor Stinner8fddc9e2010-05-18 17:24:09 +0000553 .. versionadded:: 3.2
554
Victor Stinnerb745a742010-05-18 17:17:23 +0000555
Georg Brandl116aa622007-08-15 14:28:22 +0000556.. function:: umask(mask)
557
Benjamin Petersonf650e462010-05-06 23:03:05 +0000558 Set the current numeric umask and return the previous umask.
559
560 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562
563.. function:: uname()
564
565 .. index::
566 single: gethostname() (in module socket)
567 single: gethostbyaddr() (in module socket)
568
569 Return a 5-tuple containing information identifying the current operating
570 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
571 machine)``. Some systems truncate the nodename to 8 characters or to the
572 leading component; a better way to get the hostname is
573 :func:`socket.gethostname` or even
Benjamin Petersonf650e462010-05-06 23:03:05 +0000574 ``socket.gethostbyaddr(socket.gethostname())``.
575
576 Availability: recent flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000577
578
Georg Brandl18244152009-09-02 20:34:52 +0000579.. function:: unsetenv(key)
Georg Brandl116aa622007-08-15 14:28:22 +0000580
581 .. index:: single: environment variables; deleting
582
Georg Brandl18244152009-09-02 20:34:52 +0000583 Unset (delete) the environment variable named *key*. Such changes to the
Georg Brandl116aa622007-08-15 14:28:22 +0000584 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
Benjamin Petersonf650e462010-05-06 23:03:05 +0000585 :func:`fork` and :func:`execv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000586
587 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
588 automatically translated into a corresponding call to :func:`unsetenv`; however,
589 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
590 preferable to delete items of ``os.environ``.
591
Benjamin Petersonf650e462010-05-06 23:03:05 +0000592 Availability: most flavors of Unix, Windows.
593
Georg Brandl116aa622007-08-15 14:28:22 +0000594
595.. _os-newstreams:
596
597File Object Creation
598--------------------
599
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000600These functions create new :term:`file objects <file object>`. (See also :func:`open`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000601
602
603.. function:: fdopen(fd[, mode[, bufsize]])
604
605 .. index:: single: I/O control; buffering
606
607 Return an open file object connected to the file descriptor *fd*. The *mode*
608 and *bufsize* arguments have the same meaning as the corresponding arguments to
Benjamin Petersonf650e462010-05-06 23:03:05 +0000609 the built-in :func:`open` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000610
Georg Brandl55ac8f02007-09-01 13:51:09 +0000611 When specified, the *mode* argument must start with one of the letters
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100612 ``'r'``, ``'w'``, ``'x'`` or ``'a'``, otherwise a :exc:`ValueError` is
613 raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000614
Georg Brandl55ac8f02007-09-01 13:51:09 +0000615 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
Georg Brandl60203b42010-10-06 10:11:56 +0000616 set on the file descriptor (which the :c:func:`fdopen` implementation already
Georg Brandl55ac8f02007-09-01 13:51:09 +0000617 does on most platforms).
Georg Brandl116aa622007-08-15 14:28:22 +0000618
Benjamin Petersonf650e462010-05-06 23:03:05 +0000619 Availability: Unix, Windows.
620
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100621 .. versionchanged:: 3.3
622 The ``'x'`` mode was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000623
Georg Brandl116aa622007-08-15 14:28:22 +0000624.. _os-fd-ops:
625
626File Descriptor Operations
627--------------------------
628
629These functions operate on I/O streams referenced using file descriptors.
630
631File descriptors are small integers corresponding to a file that has been opened
632by the current process. For example, standard input is usually file descriptor
6330, standard output is 1, and standard error is 2. Further files opened by a
634process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
635is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
636by file descriptors.
637
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000638The :meth:`~file.fileno` method can be used to obtain the file descriptor
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000639associated with a :term:`file object` when required. Note that using the file
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000640descriptor directly will bypass the file object methods, ignoring aspects such
641as internal buffering of data.
Georg Brandl116aa622007-08-15 14:28:22 +0000642
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000643.. data:: AT_SYMLINK_NOFOLLOW
644 AT_EACCESS
645 AT_FDCWD
646 AT_REMOVEDIR
647 AT_SYMLINK_FOLLOW
648 UTIME_NOW
649 UTIME_OMIT
650
651 These parameters are used as flags to the \*at family of functions.
652
653 Availability: Unix.
654
655 .. versionadded:: 3.3
656
657
Georg Brandl116aa622007-08-15 14:28:22 +0000658.. function:: close(fd)
659
Benjamin Petersonf650e462010-05-06 23:03:05 +0000660 Close file descriptor *fd*.
661
662 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000663
664 .. note::
665
666 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000667 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
Georg Brandl116aa622007-08-15 14:28:22 +0000668 object" returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000669 :func:`fdopen`, use its :meth:`~file.close` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000670
671
Christian Heimesfdab48e2008-01-20 09:06:41 +0000672.. function:: closerange(fd_low, fd_high)
673
674 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
Benjamin Petersonf650e462010-05-06 23:03:05 +0000675 ignoring errors. Equivalent to::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000676
Georg Brandlc9a5a0e2009-09-01 07:34:27 +0000677 for fd in range(fd_low, fd_high):
Christian Heimesfdab48e2008-01-20 09:06:41 +0000678 try:
679 os.close(fd)
680 except OSError:
681 pass
682
Benjamin Petersonf650e462010-05-06 23:03:05 +0000683 Availability: Unix, Windows.
684
Christian Heimesfdab48e2008-01-20 09:06:41 +0000685
Georg Brandl81f11302007-12-21 08:45:42 +0000686.. function:: device_encoding(fd)
687
688 Return a string describing the encoding of the device associated with *fd*
689 if it is connected to a terminal; else return :const:`None`.
690
691
Georg Brandl116aa622007-08-15 14:28:22 +0000692.. function:: dup(fd)
693
Benjamin Petersonf650e462010-05-06 23:03:05 +0000694 Return a duplicate of file descriptor *fd*.
695
696 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698
699.. function:: dup2(fd, fd2)
700
701 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000702
Georg Brandlc575c902008-09-13 17:46:05 +0000703 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000704
705
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000706.. function:: faccessat(dirfd, path, mode, flags=0)
707
708 Like :func:`access` but if *path* is relative, it is taken as relative to *dirfd*.
709 *flags* is optional and can be constructed by ORing together zero or more
710 of these values: :data:`AT_SYMLINK_NOFOLLOW`, :data:`AT_EACCESS`.
711 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
712 is interpreted relative to the current working directory.
713
714 Availability: Unix.
715
716 .. versionadded:: 3.3
717
718
Christian Heimes4e30a842007-11-30 22:12:06 +0000719.. function:: fchmod(fd, mode)
720
721 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
Benjamin Petersonf650e462010-05-06 23:03:05 +0000722 for :func:`chmod` for possible values of *mode*.
723
724 Availability: Unix.
Christian Heimes4e30a842007-11-30 22:12:06 +0000725
726
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000727.. function:: fchmodat(dirfd, path, mode, flags=0)
728
729 Like :func:`chmod` but if *path* is relative, it is taken as relative to *dirfd*.
730 *flags* is optional and may be 0 or :data:`AT_SYMLINK_NOFOLLOW`.
731 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
732 is interpreted relative to the current working directory.
733
734 Availability: Unix.
735
736 .. versionadded:: 3.3
737
738
Christian Heimes4e30a842007-11-30 22:12:06 +0000739.. function:: fchown(fd, uid, gid)
740
741 Change the owner and group id of the file given by *fd* to the numeric *uid*
742 and *gid*. To leave one of the ids unchanged, set it to -1.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000743
Christian Heimes4e30a842007-11-30 22:12:06 +0000744 Availability: Unix.
745
746
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000747.. function:: fchownat(dirfd, path, uid, gid, flags=0)
748
749 Like :func:`chown` but if *path* is relative, it is taken as relative to *dirfd*.
750 *flags* is optional and may be 0 or :data:`AT_SYMLINK_NOFOLLOW`.
751 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
752 is interpreted relative to the current working directory.
753
754 Availability: Unix.
755
756 .. versionadded:: 3.3
757
758
Georg Brandl116aa622007-08-15 14:28:22 +0000759.. function:: fdatasync(fd)
760
761 Force write of file with filedescriptor *fd* to disk. Does not force update of
Benjamin Petersonf650e462010-05-06 23:03:05 +0000762 metadata.
763
764 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000765
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000766 .. note::
767 This function is not available on MacOS.
768
Georg Brandl116aa622007-08-15 14:28:22 +0000769
Benjamin Peterson799bd802011-08-31 22:15:17 -0400770.. function:: fgetxattr(fd, attr)
771
772 This works exactly like :func:`getxattr` but operates on a file descriptor,
773 *fd*, instead of a path.
774
775 Availability: Linux
776
777 .. versionadded:: 3.3
778
779
780.. function:: flistxattr(fd)
781
782 This is exactly like :func:`listxattr` but operates on a file descriptor,
783 *fd*, instead of a path.
784
785 Availability: Linux
786
787 .. versionadded:: 3.3
788
789
Charles-François Natali77940902012-02-06 19:54:48 +0100790.. function:: flistdir(fd)
Antoine Pitrou8250e232011-02-25 23:41:16 +0000791
792 Like :func:`listdir`, but uses a file descriptor instead and always returns
Charles-François Natali76961fa2012-01-10 20:25:09 +0100793 strings.
Antoine Pitrou8250e232011-02-25 23:41:16 +0000794
795 Availability: Unix.
796
797 .. versionadded:: 3.3
798
799
Ross Lagerwall7807c352011-03-17 20:20:30 +0200800.. function:: fexecve(fd, args, env)
801
802 Execute the program specified by a file descriptor *fd* with arguments given
803 by *args* and environment given by *env*, replacing the current process.
804 *args* and *env* are given as in :func:`execve`.
805
806 Availability: Unix.
807
808 .. versionadded:: 3.3
809
810
Georg Brandl116aa622007-08-15 14:28:22 +0000811.. function:: fpathconf(fd, name)
812
813 Return system configuration information relevant to an open file. *name*
814 specifies the configuration value to retrieve; it may be a string which is the
815 name of a defined system value; these names are specified in a number of
816 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
817 additional names as well. The names known to the host operating system are
818 given in the ``pathconf_names`` dictionary. For configuration variables not
819 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +0000820
821 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
822 specific value for *name* is not supported by the host system, even if it is
823 included in ``pathconf_names``, an :exc:`OSError` is raised with
824 :const:`errno.EINVAL` for the error number.
825
Benjamin Petersonf650e462010-05-06 23:03:05 +0000826 Availability: Unix.
827
Georg Brandl116aa622007-08-15 14:28:22 +0000828
Victor Stinner4195b5c2012-02-08 23:03:19 +0100829.. function:: fstat(fd)
Georg Brandl116aa622007-08-15 14:28:22 +0000830
R. David Murray7b1aae92011-01-24 19:34:58 +0000831 Return status for file descriptor *fd*, like :func:`~os.stat`.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000832
833 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000834
Victor Stinner4195b5c2012-02-08 23:03:19 +0100835.. function:: fstatat(dirfd, path, flags=0)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000836
837 Like :func:`stat` but if *path* is relative, it is taken as relative to *dirfd*.
838 *flags* is optional and may be 0 or :data:`AT_SYMLINK_NOFOLLOW`.
839 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
840 is interpreted relative to the current working directory.
841
842 Availability: Unix.
843
844 .. versionadded:: 3.3
845
Georg Brandl116aa622007-08-15 14:28:22 +0000846
847.. function:: fstatvfs(fd)
848
849 Return information about the filesystem containing the file associated with file
Benjamin Petersonf650e462010-05-06 23:03:05 +0000850 descriptor *fd*, like :func:`statvfs`.
851
852 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000853
854
855.. function:: fsync(fd)
856
857 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
Georg Brandl60203b42010-10-06 10:11:56 +0000858 native :c:func:`fsync` function; on Windows, the MS :c:func:`_commit` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000859
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000860 If you're starting with a buffered Python :term:`file object` *f*, first do
861 ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal
862 buffers associated with *f* are written to disk.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000863
864 Availability: Unix, and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000865
866
867.. function:: ftruncate(fd, length)
868
869 Truncate the file corresponding to file descriptor *fd*, so that it is at most
Benjamin Petersonf650e462010-05-06 23:03:05 +0000870 *length* bytes in size.
871
872 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000873
874
Benjamin Peterson799bd802011-08-31 22:15:17 -0400875.. function:: fremovexattr(fd, attr)
876
877 This works exactly like :func:`removexattr` but operates on a file
878 descriptor, *fd*, instead of a path.
879
880 Availability: Linux
881
882 .. versionadded:: 3.3
883
884
885.. function:: fsetxattr(fd, attr, value, flags=0)
886
887 This works exactly like :func:`setxattr` but on a file descriptor, *fd*,
888 instead of a path.
889
890
891 Availability: Linux
892
893 .. versionadded:: 3.3
894
895
Ezio Melotti257a14c2011-11-09 00:25:47 +0200896.. function:: futimesat(dirfd, path[, times])
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000897
898 Like :func:`utime` but if *path* is relative, it is taken as relative to *dirfd*.
899 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
Ezio Melotti257a14c2011-11-09 00:25:47 +0200900 is interpreted relative to the current working directory. *times* must be a
901 2-tuple of numbers, of the form ``(atime, mtime)``, or None.
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000902
903 Availability: Unix.
904
905 .. versionadded:: 3.3
906
907
Ezio Melotti257a14c2011-11-09 00:25:47 +0200908.. function:: futimens(fd[, atimes, mtimes])
Ross Lagerwall7807c352011-03-17 20:20:30 +0200909
910 Updates the timestamps of a file specified by the file descriptor *fd*, with
911 nanosecond precision.
Brian Curtinc1b65d12011-11-07 14:18:54 -0600912 If no second argument is given, set *atime* and *mtime* to the current time.
Ezio Melotti257a14c2011-11-09 00:25:47 +0200913 *atimes* and *mtimes* must be 2-tuples of numbers, of the form
914 ``(atime_sec, atime_nsec)`` and ``(mtime_sec, mtime_nsec)`` respectively,
915 or ``None``.
Ross Lagerwall7807c352011-03-17 20:20:30 +0200916 If *atime_nsec* or *mtime_nsec* is specified as :data:`UTIME_NOW`, the corresponding
917 timestamp is updated to the current time.
918 If *atime_nsec* or *mtime_nsec* is specified as :data:`UTIME_OMIT`, the corresponding
919 timestamp is not updated.
920
921 Availability: Unix.
922
923 .. versionadded:: 3.3
924
925
926.. data:: UTIME_NOW
927 UTIME_OMIT
928
929 Flags used with :func:`futimens` to specify that the timestamp must be
930 updated either to the current time or not updated at all.
931
932 Availability: Unix.
933
934 .. versionadded:: 3.3
935
936
Larry Hastings76ad59b2012-05-03 00:30:07 -0700937.. function:: futimes(fd[, times, *, ns=times])
Ross Lagerwall7807c352011-03-17 20:20:30 +0200938
939 Set the access and modified time of the file specified by the file
Larry Hastings76ad59b2012-05-03 00:30:07 -0700940 descriptor *fd* to the given values. See :func:`utime` for proper
941 use of the *times* and *ns* arguments.
Ross Lagerwall7807c352011-03-17 20:20:30 +0200942 Availability: Unix.
943
944 .. versionadded:: 3.3
945
946
Georg Brandl116aa622007-08-15 14:28:22 +0000947.. function:: isatty(fd)
948
949 Return ``True`` if the file descriptor *fd* is open and connected to a
Benjamin Petersonf650e462010-05-06 23:03:05 +0000950 tty(-like) device, else ``False``.
951
952 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000953
954
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000955.. function:: linkat(srcfd, srcpath, dstfd, dstpath, flags=0)
956
957 Like :func:`link` but if *srcpath* is relative, it is taken as relative to *srcfd*
958 and if *dstpath* is relative, it is taken as relative to *dstfd*.
959 *flags* is optional and may be 0 or :data:`AT_SYMLINK_FOLLOW`.
960 If *srcpath* is relative and *srcfd* is the special value :data:`AT_FDCWD`, then
961 *srcpath* is interpreted relative to the current working directory. This
962 also applies for *dstpath*.
963
964 Availability: Unix.
965
966 .. versionadded:: 3.3
967
968
Ross Lagerwall7807c352011-03-17 20:20:30 +0200969.. function:: lockf(fd, cmd, len)
970
971 Apply, test or remove a POSIX lock on an open file descriptor.
972 *fd* is an open file descriptor.
973 *cmd* specifies the command to use - one of :data:`F_LOCK`, :data:`F_TLOCK`,
974 :data:`F_ULOCK` or :data:`F_TEST`.
975 *len* specifies the section of the file to lock.
976
977 Availability: Unix.
978
979 .. versionadded:: 3.3
980
981
982.. data:: F_LOCK
983 F_TLOCK
984 F_ULOCK
985 F_TEST
986
987 Flags that specify what action :func:`lockf` will take.
988
989 Availability: Unix.
990
991 .. versionadded:: 3.3
992
Georg Brandl116aa622007-08-15 14:28:22 +0000993.. function:: lseek(fd, pos, how)
994
Christian Heimesfaf2f632008-01-06 16:59:19 +0000995 Set the current position of file descriptor *fd* to position *pos*, modified
996 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
997 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
998 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Victor Stinnere83f8992011-12-17 23:15:09 +0100999 the file. Return the new cursor position in bytes, starting from the beginning.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001000
1001 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001002
1003
Georg Brandl8569e582010-05-19 20:57:08 +00001004.. data:: SEEK_SET
1005 SEEK_CUR
1006 SEEK_END
1007
1008 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
1009 respectively. Availability: Windows, Unix.
1010
1011
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001012.. function:: mkdirat(dirfd, path, mode=0o777)
1013
1014 Like :func:`mkdir` but if *path* is relative, it is taken as relative to *dirfd*.
1015 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
1016 is interpreted relative to the current working directory.
1017
1018 Availability: Unix.
1019
1020 .. versionadded:: 3.3
1021
1022
1023.. function:: mkfifoat(dirfd, path, mode=0o666)
1024
1025 Like :func:`mkfifo` but if *path* is relative, it is taken as relative to *dirfd*.
1026 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
1027 is interpreted relative to the current working directory.
1028
1029 Availability: Unix.
1030
1031 .. versionadded:: 3.3
1032
1033
1034.. function:: mknodat(dirfd, path, mode=0o600, device=0)
1035
1036 Like :func:`mknod` but if *path* is relative, it is taken as relative to *dirfd*.
1037 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
1038 is interpreted relative to the current working directory.
1039
1040 Availability: Unix.
1041
1042 .. versionadded:: 3.3
1043
1044
Georg Brandl116aa622007-08-15 14:28:22 +00001045.. function:: open(file, flags[, mode])
1046
Georg Brandlf4a41232008-05-26 17:55:52 +00001047 Open the file *file* and set various flags according to *flags* and possibly
1048 its mode according to *mode*. The default *mode* is ``0o777`` (octal), and
1049 the current umask value is first masked out. Return the file descriptor for
Benjamin Petersonf650e462010-05-06 23:03:05 +00001050 the newly opened file.
Georg Brandl116aa622007-08-15 14:28:22 +00001051
1052 For a description of the flag and mode values, see the C run-time documentation;
1053 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
Georg Brandl8569e582010-05-19 20:57:08 +00001054 this module too (see :ref:`open-constants`). In particular, on Windows adding
1055 :const:`O_BINARY` is needed to open files in binary mode.
Georg Brandl116aa622007-08-15 14:28:22 +00001056
Benjamin Petersonf650e462010-05-06 23:03:05 +00001057 Availability: Unix, Windows.
1058
Georg Brandl116aa622007-08-15 14:28:22 +00001059 .. note::
1060
Georg Brandl502d9a52009-07-26 15:02:41 +00001061 This function is intended for low-level I/O. For normal usage, use the
Antoine Pitrou11cb9612010-09-15 11:11:28 +00001062 built-in function :func:`open`, which returns a :term:`file object` with
Jeroen Ruigrok van der Werven9c558bc2010-07-13 14:47:01 +00001063 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
Antoine Pitrou11cb9612010-09-15 11:11:28 +00001064 wrap a file descriptor in a file object, use :func:`fdopen`.
Georg Brandl116aa622007-08-15 14:28:22 +00001065
1066
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001067.. function:: openat(dirfd, path, flags, mode=0o777)
1068
1069 Like :func:`open` but if *path* is relative, it is taken as relative to *dirfd*.
1070 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
1071 is interpreted relative to the current working directory.
1072
1073 Availability: Unix.
1074
1075 .. versionadded:: 3.3
1076
1077
Georg Brandl116aa622007-08-15 14:28:22 +00001078.. function:: openpty()
1079
1080 .. index:: module: pty
1081
1082 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
1083 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Benjamin Petersonf650e462010-05-06 23:03:05 +00001084 approach, use the :mod:`pty` module.
1085
1086 Availability: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001087
1088
1089.. function:: pipe()
1090
1091 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
Benjamin Petersonf650e462010-05-06 23:03:05 +00001092 and writing, respectively.
1093
1094 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001095
1096
Charles-François Natali368f34b2011-06-06 19:49:47 +02001097.. function:: pipe2(flags)
Charles-François Natalidaafdd52011-05-29 20:07:40 +02001098
1099 Create a pipe with *flags* set atomically.
Charles-François Natali368f34b2011-06-06 19:49:47 +02001100 *flags* can be constructed by ORing together one or more of these values:
1101 :data:`O_NONBLOCK`, :data:`O_CLOEXEC`.
Charles-François Natalidaafdd52011-05-29 20:07:40 +02001102 Return a pair of file descriptors ``(r, w)`` usable for reading and writing,
1103 respectively.
1104
1105 Availability: some flavors of Unix.
1106
1107 .. versionadded:: 3.3
1108
1109
Ross Lagerwall7807c352011-03-17 20:20:30 +02001110.. function:: posix_fallocate(fd, offset, len)
1111
1112 Ensures that enough disk space is allocated for the file specified by *fd*
1113 starting from *offset* and continuing for *len* bytes.
1114
1115 Availability: Unix.
1116
1117 .. versionadded:: 3.3
1118
1119
1120.. function:: posix_fadvise(fd, offset, len, advice)
1121
1122 Announces an intention to access data in a specific pattern thus allowing
1123 the kernel to make optimizations.
1124 The advice applies to the region of the file specified by *fd* starting at
1125 *offset* and continuing for *len* bytes.
1126 *advice* is one of :data:`POSIX_FADV_NORMAL`, :data:`POSIX_FADV_SEQUENTIAL`,
1127 :data:`POSIX_FADV_RANDOM`, :data:`POSIX_FADV_NOREUSE`,
1128 :data:`POSIX_FADV_WILLNEED` or :data:`POSIX_FADV_DONTNEED`.
1129
1130 Availability: Unix.
1131
1132 .. versionadded:: 3.3
1133
1134
1135.. data:: POSIX_FADV_NORMAL
1136 POSIX_FADV_SEQUENTIAL
1137 POSIX_FADV_RANDOM
1138 POSIX_FADV_NOREUSE
1139 POSIX_FADV_WILLNEED
1140 POSIX_FADV_DONTNEED
1141
1142 Flags that can be used in *advice* in :func:`posix_fadvise` that specify
1143 the access pattern that is likely to be used.
1144
1145 Availability: Unix.
1146
1147 .. versionadded:: 3.3
1148
1149
1150.. function:: pread(fd, buffersize, offset)
1151
1152 Read from a file descriptor, *fd*, at a position of *offset*. It will read up
1153 to *buffersize* number of bytes. The file offset remains unchanged.
1154
1155 Availability: Unix.
1156
1157 .. versionadded:: 3.3
1158
1159
1160.. function:: pwrite(fd, string, offset)
1161
1162 Write *string* to a file descriptor, *fd*, from *offset*, leaving the file
1163 offset unchanged.
1164
1165 Availability: Unix.
1166
1167 .. versionadded:: 3.3
1168
1169
Georg Brandl116aa622007-08-15 14:28:22 +00001170.. function:: read(fd, n)
1171
Georg Brandlb90be692009-07-29 16:14:16 +00001172 Read at most *n* bytes from file descriptor *fd*. Return a bytestring containing the
Georg Brandl116aa622007-08-15 14:28:22 +00001173 bytes read. If the end of the file referred to by *fd* has been reached, an
Benjamin Petersonf650e462010-05-06 23:03:05 +00001174 empty bytes object is returned.
1175
1176 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001177
1178 .. note::
1179
1180 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001181 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a "file object"
Georg Brandl116aa622007-08-15 14:28:22 +00001182 returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001183 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
1184 :meth:`~file.readline` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00001185
1186
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001187.. function:: sendfile(out, in, offset, nbytes)
1188 sendfile(out, in, offset, nbytes, headers=None, trailers=None, flags=0)
1189
1190 Copy *nbytes* bytes from file descriptor *in* to file descriptor *out*
1191 starting at *offset*.
1192 Return the number of bytes sent. When EOF is reached return 0.
1193
1194 The first function notation is supported by all platforms that define
1195 :func:`sendfile`.
1196
1197 On Linux, if *offset* is given as ``None``, the bytes are read from the
1198 current position of *in* and the position of *in* is updated.
1199
1200 The second case may be used on Mac OS X and FreeBSD where *headers* and
1201 *trailers* are arbitrary sequences of buffers that are written before and
1202 after the data from *in* is written. It returns the same as the first case.
1203
1204 On Mac OS X and FreeBSD, a value of 0 for *nbytes* specifies to send until
1205 the end of *in* is reached.
1206
1207 On Solaris, *out* may be the file descriptor of a regular file or the file
1208 descriptor of a socket. On all other platforms, *out* must be the file
1209 descriptor of an open socket.
1210
1211 Availability: Unix.
1212
1213 .. versionadded:: 3.3
1214
1215
1216.. data:: SF_NODISKIO
1217 SF_MNOWAIT
1218 SF_SYNC
1219
1220 Parameters to the :func:`sendfile` function, if the implementation supports
1221 them.
1222
1223 Availability: Unix.
1224
1225 .. versionadded:: 3.3
1226
1227
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001228.. function:: readlinkat(dirfd, path)
1229
1230 Like :func:`readlink` but if *path* is relative, it is taken as relative to *dirfd*.
1231 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
1232 is interpreted relative to the current working directory.
1233
1234 Availability: Unix.
1235
1236 .. versionadded:: 3.3
1237
1238
1239.. function:: renameat(olddirfd, oldpath, newdirfd, newpath)
1240
1241 Like :func:`rename` but if *oldpath* is relative, it is taken as relative to
1242 *olddirfd* and if *newpath* is relative, it is taken as relative to *newdirfd*.
1243 If *oldpath* is relative and *olddirfd* is the special value :data:`AT_FDCWD`, then
1244 *oldpath* is interpreted relative to the current working directory. This
1245 also applies for *newpath*.
1246
1247 Availability: Unix.
1248
1249 .. versionadded:: 3.3
1250
1251
1252.. function:: symlinkat(src, dstfd, dst)
1253
1254 Like :func:`symlink` but if *dst* is relative, it is taken as relative to *dstfd*.
1255 If *dst* is relative and *dstfd* is the special value :data:`AT_FDCWD`, then *dst*
1256 is interpreted relative to the current working directory.
1257
1258 Availability: Unix.
1259
1260 .. versionadded:: 3.3
1261
1262
Ross Lagerwall7807c352011-03-17 20:20:30 +02001263.. function:: readv(fd, buffers)
1264
1265 Read from a file descriptor into a number of writable buffers. *buffers* is
1266 an arbitrary sequence of writable buffers. Returns the total number of bytes
1267 read.
1268
1269 Availability: Unix.
1270
1271 .. versionadded:: 3.3
1272
1273
Georg Brandl116aa622007-08-15 14:28:22 +00001274.. function:: tcgetpgrp(fd)
1275
1276 Return the process group associated with the terminal given by *fd* (an open
Benjamin Petersonf650e462010-05-06 23:03:05 +00001277 file descriptor as returned by :func:`os.open`).
1278
1279 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001280
1281
1282.. function:: tcsetpgrp(fd, pg)
1283
1284 Set the process group associated with the terminal given by *fd* (an open file
Benjamin Petersonf650e462010-05-06 23:03:05 +00001285 descriptor as returned by :func:`os.open`) to *pg*.
1286
1287 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001288
1289
1290.. function:: ttyname(fd)
1291
1292 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +00001293 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Benjamin Petersonf650e462010-05-06 23:03:05 +00001294 exception is raised.
1295
1296 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001297
1298
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001299.. function:: unlinkat(dirfd, path, flags=0)
1300
1301 Like :func:`unlink` but if *path* is relative, it is taken as relative to *dirfd*.
1302 *flags* is optional and may be 0 or :data:`AT_REMOVEDIR`. If :data:`AT_REMOVEDIR` is
1303 specified, :func:`unlinkat` behaves like :func:`rmdir`.
1304 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
1305 is interpreted relative to the current working directory.
1306
1307 Availability: Unix.
1308
1309 .. versionadded:: 3.3
1310
1311
Brian Curtin4b6fabd2011-11-08 14:54:02 -06001312.. function:: utimensat(dirfd, path[, atime=(atime_sec, atime_nsec), mtime=(mtime_sec, mtime_nsec), flags=0])
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001313
1314 Updates the timestamps of a file with nanosecond precision.
Brian Curtin569b4942011-11-07 16:09:20 -06001315 The *atime* and *mtime* tuples default to ``None``, which sets those
1316 values to the current time.
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001317 If *atime_nsec* or *mtime_nsec* is specified as :data:`UTIME_NOW`, the corresponding
1318 timestamp is updated to the current time.
1319 If *atime_nsec* or *mtime_nsec* is specified as :data:`UTIME_OMIT`, the corresponding
1320 timestamp is not updated.
1321 If *path* is relative, it is taken as relative to *dirfd*.
Brian Curtin569b4942011-11-07 16:09:20 -06001322 *flags* is optional and may be 0 (the default) or :data:`AT_SYMLINK_NOFOLLOW`.
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001323 If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
1324 is interpreted relative to the current working directory.
1325
1326 Availability: Unix.
1327
1328 .. versionadded:: 3.3
1329
1330
Georg Brandl116aa622007-08-15 14:28:22 +00001331.. function:: write(fd, str)
1332
Georg Brandlb90be692009-07-29 16:14:16 +00001333 Write the bytestring in *str* to file descriptor *fd*. Return the number of
Benjamin Petersonf650e462010-05-06 23:03:05 +00001334 bytes actually written.
1335
1336 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001337
1338 .. note::
1339
1340 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001341 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
Georg Brandl116aa622007-08-15 14:28:22 +00001342 object" returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001343 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
1344 :meth:`~file.write` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001345
Georg Brandl8569e582010-05-19 20:57:08 +00001346
Ross Lagerwall7807c352011-03-17 20:20:30 +02001347.. function:: writev(fd, buffers)
1348
Ezio Melottif1064492011-10-19 11:06:26 +03001349 Write the contents of *buffers* to file descriptor *fd*, where *buffers*
Ross Lagerwall7807c352011-03-17 20:20:30 +02001350 is an arbitrary sequence of buffers.
1351 Returns the total number of bytes written.
1352
1353 Availability: Unix.
1354
1355 .. versionadded:: 3.3
1356
1357
Georg Brandl8569e582010-05-19 20:57:08 +00001358.. _open-constants:
1359
1360``open()`` flag constants
1361~~~~~~~~~~~~~~~~~~~~~~~~~
1362
Georg Brandlaf265f42008-12-07 15:06:20 +00001363The following constants are options for the *flags* parameter to the
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001364:func:`~os.open` function. They can be combined using the bitwise OR operator
Georg Brandlaf265f42008-12-07 15:06:20 +00001365``|``. Some of them are not available on all platforms. For descriptions of
1366their availability and use, consult the :manpage:`open(2)` manual page on Unix
Doug Hellmanneb097fc2009-09-20 20:56:56 +00001367or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001368
1369
1370.. data:: O_RDONLY
1371 O_WRONLY
1372 O_RDWR
1373 O_APPEND
1374 O_CREAT
1375 O_EXCL
1376 O_TRUNC
1377
Georg Brandlaf265f42008-12-07 15:06:20 +00001378 These constants are available on Unix and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001379
1380
1381.. data:: O_DSYNC
1382 O_RSYNC
1383 O_SYNC
1384 O_NDELAY
1385 O_NONBLOCK
1386 O_NOCTTY
1387 O_SHLOCK
1388 O_EXLOCK
Charles-François Natali1e045b12011-05-22 20:42:32 +02001389 O_CLOEXEC
Georg Brandl116aa622007-08-15 14:28:22 +00001390
Georg Brandlaf265f42008-12-07 15:06:20 +00001391 These constants are only available on Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001392
Victor Stinnere3455c02011-10-20 00:46:21 +02001393 .. versionchanged:: 3.3
1394 Add :data:`O_CLOEXEC` constant.
Georg Brandl116aa622007-08-15 14:28:22 +00001395
1396.. data:: O_BINARY
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001397 O_NOINHERIT
Georg Brandl116aa622007-08-15 14:28:22 +00001398 O_SHORT_LIVED
1399 O_TEMPORARY
1400 O_RANDOM
1401 O_SEQUENTIAL
1402 O_TEXT
1403
Georg Brandlaf265f42008-12-07 15:06:20 +00001404 These constants are only available on Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001405
1406
Alexandre Vassalottibee32532008-05-16 18:15:12 +00001407.. data:: O_ASYNC
1408 O_DIRECT
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001409 O_DIRECTORY
1410 O_NOFOLLOW
1411 O_NOATIME
1412
Georg Brandlaf265f42008-12-07 15:06:20 +00001413 These constants are GNU extensions and not present if they are not defined by
1414 the C library.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001415
1416
Victor Stinner8b905bd2011-10-25 13:34:04 +02001417.. data:: RTLD_LAZY
1418 RTLD_NOW
1419 RTLD_GLOBAL
1420 RTLD_LOCAL
1421 RTLD_NODELETE
1422 RTLD_NOLOAD
1423 RTLD_DEEPBIND
1424
1425 See the Unix manual page :manpage:`dlopen(3)`.
1426
1427 .. versionadded:: 3.3
1428
1429
Antoine Pitroubcf2b592012-02-08 23:28:36 +01001430.. _terminal-size:
1431
1432Querying the size of a terminal
1433~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1434
1435.. versionadded:: 3.3
1436
1437.. function:: get_terminal_size(fd=STDOUT_FILENO)
1438
1439 Return the size of the terminal window as ``(columns, lines)``,
1440 tuple of type :class:`terminal_size`.
1441
1442 The optional argument ``fd`` (default ``STDOUT_FILENO``, or standard
1443 output) specifies which file descriptor should be queried.
1444
1445 If the file descriptor is not connected to a terminal, an :exc:`OSError`
1446 is thrown.
1447
1448 :func:`shutil.get_terminal_size` is the high-level function which
1449 should normally be used, ``os.get_terminal_size`` is the low-level
1450 implementation.
1451
1452 Availability: Unix, Windows.
1453
1454.. class:: terminal_size(tuple)
1455
1456 A tuple of ``(columns, lines)`` for holding terminal window size.
1457
1458 .. attribute:: columns
1459
1460 Width of the terminal window in characters.
1461
1462 .. attribute:: lines
1463
1464 Height of the terminal window in characters.
1465
1466
Georg Brandl116aa622007-08-15 14:28:22 +00001467.. _os-file-dir:
1468
1469Files and Directories
1470---------------------
1471
Georg Brandl116aa622007-08-15 14:28:22 +00001472.. function:: access(path, mode)
1473
1474 Use the real uid/gid to test for access to *path*. Note that most operations
1475 will use the effective uid/gid, therefore this routine can be used in a
1476 suid/sgid environment to test if the invoking user has the specified access to
1477 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
1478 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
1479 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
1480 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
Benjamin Petersonf650e462010-05-06 23:03:05 +00001481 information.
1482
1483 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001484
1485 .. note::
1486
Georg Brandl502d9a52009-07-26 15:02:41 +00001487 Using :func:`access` to check if a user is authorized to e.g. open a file
1488 before actually doing so using :func:`open` creates a security hole,
1489 because the user might exploit the short time interval between checking
Benjamin Peterson249b5082011-05-20 11:41:13 -05001490 and opening the file to manipulate it. It's preferable to use :term:`EAFP`
1491 techniques. For example::
1492
1493 if os.access("myfile", os.R_OK):
1494 with open("myfile") as fp:
1495 return fp.read()
1496 return "some default data"
1497
1498 is better written as::
1499
1500 try:
1501 fp = open("myfile")
Antoine Pitrou62ab10a2011-10-12 20:10:51 +02001502 except PermissionError:
1503 return "some default data"
Benjamin Peterson249b5082011-05-20 11:41:13 -05001504 else:
1505 with fp:
1506 return fp.read()
Georg Brandl116aa622007-08-15 14:28:22 +00001507
1508 .. note::
1509
1510 I/O operations may fail even when :func:`access` indicates that they would
1511 succeed, particularly for operations on network filesystems which may have
1512 permissions semantics beyond the usual POSIX permission-bit model.
1513
1514
1515.. data:: F_OK
1516
1517 Value to pass as the *mode* parameter of :func:`access` to test the existence of
1518 *path*.
1519
1520
1521.. data:: R_OK
1522
1523 Value to include in the *mode* parameter of :func:`access` to test the
1524 readability of *path*.
1525
1526
1527.. data:: W_OK
1528
1529 Value to include in the *mode* parameter of :func:`access` to test the
1530 writability of *path*.
1531
1532
1533.. data:: X_OK
1534
1535 Value to include in the *mode* parameter of :func:`access` to determine if
1536 *path* can be executed.
1537
1538
1539.. function:: chdir(path)
1540
1541 .. index:: single: directory; changing
1542
Benjamin Petersonf650e462010-05-06 23:03:05 +00001543 Change the current working directory to *path*.
1544
1545 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001546
1547
1548.. function:: fchdir(fd)
1549
1550 Change the current working directory to the directory represented by the file
1551 descriptor *fd*. The descriptor must refer to an opened directory, not an open
Benjamin Petersonf650e462010-05-06 23:03:05 +00001552 file.
1553
1554 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001555
Georg Brandl116aa622007-08-15 14:28:22 +00001556
1557.. function:: getcwd()
1558
Martin v. Löwis011e8422009-05-05 04:43:17 +00001559 Return a string representing the current working directory.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001560
Martin v. Löwis011e8422009-05-05 04:43:17 +00001561 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001562
Benjamin Petersonf650e462010-05-06 23:03:05 +00001563
Martin v. Löwisa731b992008-10-07 06:36:31 +00001564.. function:: getcwdb()
Georg Brandl116aa622007-08-15 14:28:22 +00001565
Georg Brandl76e55382008-10-08 16:34:57 +00001566 Return a bytestring representing the current working directory.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001567
Georg Brandlc575c902008-09-13 17:46:05 +00001568 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001569
Georg Brandl116aa622007-08-15 14:28:22 +00001570
1571.. function:: chflags(path, flags)
1572
1573 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
1574 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
1575
R David Murray30178062011-03-10 17:18:33 -05001576 * :data:`stat.UF_NODUMP`
1577 * :data:`stat.UF_IMMUTABLE`
1578 * :data:`stat.UF_APPEND`
1579 * :data:`stat.UF_OPAQUE`
1580 * :data:`stat.UF_NOUNLINK`
Ned Deily3eb67d52011-06-28 00:00:28 -07001581 * :data:`stat.UF_COMPRESSED`
1582 * :data:`stat.UF_HIDDEN`
R David Murray30178062011-03-10 17:18:33 -05001583 * :data:`stat.SF_ARCHIVED`
1584 * :data:`stat.SF_IMMUTABLE`
1585 * :data:`stat.SF_APPEND`
1586 * :data:`stat.SF_NOUNLINK`
1587 * :data:`stat.SF_SNAPSHOT`
Georg Brandl116aa622007-08-15 14:28:22 +00001588
Georg Brandlc575c902008-09-13 17:46:05 +00001589 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001590
Georg Brandl116aa622007-08-15 14:28:22 +00001591
1592.. function:: chroot(path)
1593
1594 Change the root directory of the current process to *path*. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001595 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001596
Georg Brandl116aa622007-08-15 14:28:22 +00001597
1598.. function:: chmod(path, mode)
1599
1600 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001601 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl116aa622007-08-15 14:28:22 +00001602 combinations of them:
1603
Alexandre Vassalottic22c6f22009-07-21 00:51:58 +00001604 * :data:`stat.S_ISUID`
1605 * :data:`stat.S_ISGID`
1606 * :data:`stat.S_ENFMT`
1607 * :data:`stat.S_ISVTX`
1608 * :data:`stat.S_IREAD`
1609 * :data:`stat.S_IWRITE`
1610 * :data:`stat.S_IEXEC`
1611 * :data:`stat.S_IRWXU`
1612 * :data:`stat.S_IRUSR`
1613 * :data:`stat.S_IWUSR`
1614 * :data:`stat.S_IXUSR`
1615 * :data:`stat.S_IRWXG`
1616 * :data:`stat.S_IRGRP`
1617 * :data:`stat.S_IWGRP`
1618 * :data:`stat.S_IXGRP`
1619 * :data:`stat.S_IRWXO`
1620 * :data:`stat.S_IROTH`
1621 * :data:`stat.S_IWOTH`
1622 * :data:`stat.S_IXOTH`
Georg Brandl116aa622007-08-15 14:28:22 +00001623
Georg Brandlc575c902008-09-13 17:46:05 +00001624 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001625
1626 .. note::
1627
1628 Although Windows supports :func:`chmod`, you can only set the file's read-only
1629 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
1630 constants or a corresponding integer value). All other bits are
1631 ignored.
1632
1633
1634.. function:: chown(path, uid, gid)
1635
1636 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
Benjamin Petersonf650e462010-05-06 23:03:05 +00001637 one of the ids unchanged, set it to -1.
1638
Sandro Tosid902a142011-08-22 23:28:27 +02001639 See :func:`shutil.chown` for a higher-level function that accepts names in
1640 addition to numeric ids.
1641
Benjamin Petersonf650e462010-05-06 23:03:05 +00001642 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001643
1644
Benjamin Peterson799bd802011-08-31 22:15:17 -04001645.. function:: getxattr(path, attr)
1646
1647 Return the value of the extended filesystem attribute *attr* for
1648 *path*. *attr* can be bytes or str. If it is str, it is encoded with the
1649 filesystem encoding.
1650
1651 Availability: Linux
1652
1653 .. versionadded:: 3.3
1654
1655
Georg Brandl116aa622007-08-15 14:28:22 +00001656.. function:: lchflags(path, flags)
1657
1658 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
Benjamin Petersonf650e462010-05-06 23:03:05 +00001659 follow symbolic links.
1660
1661 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001662
Georg Brandl116aa622007-08-15 14:28:22 +00001663
Christian Heimes93852662007-12-01 12:22:32 +00001664.. function:: lchmod(path, mode)
1665
1666 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
1667 affects the symlink rather than the target. See the docs for :func:`chmod`
Benjamin Petersonf650e462010-05-06 23:03:05 +00001668 for possible values of *mode*.
1669
1670 Availability: Unix.
Christian Heimes93852662007-12-01 12:22:32 +00001671
Christian Heimes93852662007-12-01 12:22:32 +00001672
Georg Brandl116aa622007-08-15 14:28:22 +00001673.. function:: lchown(path, uid, gid)
1674
Christian Heimesfaf2f632008-01-06 16:59:19 +00001675 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Benjamin Petersonf650e462010-05-06 23:03:05 +00001676 function will not follow symbolic links.
1677
1678 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001679
Georg Brandl116aa622007-08-15 14:28:22 +00001680
Benjamin Peterson799bd802011-08-31 22:15:17 -04001681.. function:: lgetxattr(path, attr)
1682
1683 This works exactly like :func:`getxattr` but doesn't follow symlinks.
1684
1685 Availability: Linux
1686
1687 .. versionadded:: 3.3
1688
1689
Benjamin Peterson5879d412009-03-30 14:51:56 +00001690.. function:: link(source, link_name)
Georg Brandl116aa622007-08-15 14:28:22 +00001691
Benjamin Petersonf650e462010-05-06 23:03:05 +00001692 Create a hard link pointing to *source* named *link_name*.
1693
Brian Curtin1b9df392010-11-24 20:24:31 +00001694 Availability: Unix, Windows.
1695
1696 .. versionchanged:: 3.2
1697 Added Windows support.
Georg Brandl116aa622007-08-15 14:28:22 +00001698
1699
Martin v. Löwis9c71f902010-07-24 10:09:11 +00001700.. function:: listdir(path='.')
Georg Brandl116aa622007-08-15 14:28:22 +00001701
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001702 Return a list containing the names of the entries in the directory given by
Martin v. Löwis9c71f902010-07-24 10:09:11 +00001703 *path* (default: ``'.'``). The list is in arbitrary order. It does not include the special
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001704 entries ``'.'`` and ``'..'`` even if they are present in the directory.
Georg Brandl116aa622007-08-15 14:28:22 +00001705
Martin v. Löwis011e8422009-05-05 04:43:17 +00001706 This function can be called with a bytes or string argument, and returns
1707 filenames of the same datatype.
Georg Brandl116aa622007-08-15 14:28:22 +00001708
Benjamin Petersonf650e462010-05-06 23:03:05 +00001709 Availability: Unix, Windows.
1710
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +00001711 .. versionchanged:: 3.2
1712 The *path* parameter became optional.
Georg Brandl116aa622007-08-15 14:28:22 +00001713
Benjamin Peterson799bd802011-08-31 22:15:17 -04001714
1715.. function:: listxattr(path)
1716
1717 Return a list of the extended filesystem attributes on *path*. Attributes are
1718 returned as string decoded with the filesystem encoding.
1719
1720 Availability: Linux
1721
1722 .. versionadded:: 3.3
1723
1724
1725.. function:: llistxattr(path)
1726
1727 This works exactly like :func:`listxattr` but doesn't follow symlinks.
1728
1729 Availability: Linux
1730
1731 .. versionadded:: 3.3
1732
1733
Victor Stinner69db2db2011-10-14 00:07:53 +02001734.. function:: lremovexattr(path, attr)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001735
Victor Stinner69db2db2011-10-14 00:07:53 +02001736 This works exactly like :func:`removexattr` but doesn't follow symlinks.
Benjamin Peterson799bd802011-08-31 22:15:17 -04001737
1738 Availability: Linux
1739
1740 .. versionadded:: 3.3
1741
1742
1743.. function:: lsetxattr(path, attr, value, flags=0)
1744
1745 This works exactly like :func:`setxattr` but doesn't follow symlinks.
1746
1747 Availability: Linux
1748
1749 .. versionadded:: 3.3
1750
1751
Victor Stinner4195b5c2012-02-08 23:03:19 +01001752.. function:: lstat(path)
Georg Brandl116aa622007-08-15 14:28:22 +00001753
R. David Murray7b1aae92011-01-24 19:34:58 +00001754 Perform the equivalent of an :c:func:`lstat` system call on the given path.
1755 Similar to :func:`~os.stat`, but does not follow symbolic links. On
1756 platforms that do not support symbolic links, this is an alias for
1757 :func:`~os.stat`.
Brian Curtinc7395692010-07-09 15:15:09 +00001758
Georg Brandlb3823372010-07-10 08:58:37 +00001759 .. versionchanged:: 3.2
1760 Added support for Windows 6.0 (Vista) symbolic links.
Georg Brandl116aa622007-08-15 14:28:22 +00001761
1762
Larry Hastings76ad59b2012-05-03 00:30:07 -07001763.. function:: lutimes(path[, times, *, ns=times])
Ross Lagerwall7807c352011-03-17 20:20:30 +02001764
1765 Like :func:`utime`, but if *path* is a symbolic link, it is not
Larry Hastings76ad59b2012-05-03 00:30:07 -07001766 dereferenced. See :func:`utime` for proper use of the
1767 *times* and *ns* arguments.
Ross Lagerwall7807c352011-03-17 20:20:30 +02001768
1769 Availability: Unix.
1770
1771 .. versionadded:: 3.3
1772
1773
Georg Brandl116aa622007-08-15 14:28:22 +00001774.. function:: mkfifo(path[, mode])
1775
Georg Brandlf4a41232008-05-26 17:55:52 +00001776 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The
1777 default *mode* is ``0o666`` (octal). The current umask value is first masked
Benjamin Petersonf650e462010-05-06 23:03:05 +00001778 out from the mode.
Georg Brandl116aa622007-08-15 14:28:22 +00001779
1780 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
1781 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
1782 rendezvous between "client" and "server" type processes: the server opens the
1783 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
1784 doesn't open the FIFO --- it just creates the rendezvous point.
1785
Benjamin Petersonf650e462010-05-06 23:03:05 +00001786 Availability: Unix.
1787
Georg Brandl116aa622007-08-15 14:28:22 +00001788
Georg Brandl18244152009-09-02 20:34:52 +00001789.. function:: mknod(filename[, mode=0o600[, device]])
Georg Brandl116aa622007-08-15 14:28:22 +00001790
1791 Create a filesystem node (file, device special file or named pipe) named
Georg Brandl18244152009-09-02 20:34:52 +00001792 *filename*. *mode* specifies both the permissions to use and the type of node
1793 to be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
1794 ``stat.S_IFCHR``, ``stat.S_IFBLK``, and ``stat.S_IFIFO`` (those constants are
1795 available in :mod:`stat`). For ``stat.S_IFCHR`` and ``stat.S_IFBLK``,
1796 *device* defines the newly created device special file (probably using
Georg Brandl116aa622007-08-15 14:28:22 +00001797 :func:`os.makedev`), otherwise it is ignored.
1798
Georg Brandl116aa622007-08-15 14:28:22 +00001799
1800.. function:: major(device)
1801
Christian Heimesfaf2f632008-01-06 16:59:19 +00001802 Extract the device major number from a raw device number (usually the
Georg Brandl60203b42010-10-06 10:11:56 +00001803 :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).
Georg Brandl116aa622007-08-15 14:28:22 +00001804
Georg Brandl116aa622007-08-15 14:28:22 +00001805
1806.. function:: minor(device)
1807
Christian Heimesfaf2f632008-01-06 16:59:19 +00001808 Extract the device minor number from a raw device number (usually the
Georg Brandl60203b42010-10-06 10:11:56 +00001809 :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).
Georg Brandl116aa622007-08-15 14:28:22 +00001810
Georg Brandl116aa622007-08-15 14:28:22 +00001811
1812.. function:: makedev(major, minor)
1813
Christian Heimesfaf2f632008-01-06 16:59:19 +00001814 Compose a raw device number from the major and minor device numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001815
Georg Brandl116aa622007-08-15 14:28:22 +00001816
1817.. function:: mkdir(path[, mode])
1818
Georg Brandlf4a41232008-05-26 17:55:52 +00001819 Create a directory named *path* with numeric mode *mode*. The default *mode*
1820 is ``0o777`` (octal). On some systems, *mode* is ignored. Where it is used,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001821 the current umask value is first masked out. If the directory already
1822 exists, :exc:`OSError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001823
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001824 It is also possible to create temporary directories; see the
1825 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1826
Benjamin Petersonf650e462010-05-06 23:03:05 +00001827 Availability: Unix, Windows.
1828
Georg Brandl116aa622007-08-15 14:28:22 +00001829
Georg Brandlc1673682010-12-02 09:06:12 +00001830.. function:: makedirs(path, mode=0o777, exist_ok=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001831
1832 .. index::
1833 single: directory; creating
1834 single: UNC paths; and os.makedirs()
1835
1836 Recursive directory creation function. Like :func:`mkdir`, but makes all
Terry Reedy5a22b652010-12-02 07:05:56 +00001837 intermediate-level directories needed to contain the leaf directory. If
Georg Brandlc1673682010-12-02 09:06:12 +00001838 the target directory with the same mode as specified already exists,
Terry Reedy5a22b652010-12-02 07:05:56 +00001839 raises an :exc:`OSError` exception if *exist_ok* is False, otherwise no
1840 exception is raised. If the directory cannot be created in other cases,
1841 raises an :exc:`OSError` exception. The default *mode* is ``0o777`` (octal).
Georg Brandlc1673682010-12-02 09:06:12 +00001842 On some systems, *mode* is ignored. Where it is used, the current umask
Terry Reedy5a22b652010-12-02 07:05:56 +00001843 value is first masked out.
Georg Brandl116aa622007-08-15 14:28:22 +00001844
1845 .. note::
1846
Georg Brandlc1673682010-12-02 09:06:12 +00001847 :func:`makedirs` will become confused if the path elements to create
1848 include :data:`pardir`.
Georg Brandl116aa622007-08-15 14:28:22 +00001849
Georg Brandl55ac8f02007-09-01 13:51:09 +00001850 This function handles UNC paths correctly.
Georg Brandl116aa622007-08-15 14:28:22 +00001851
Terry Reedy5a22b652010-12-02 07:05:56 +00001852 .. versionadded:: 3.2
1853 The *exist_ok* parameter.
1854
Georg Brandl116aa622007-08-15 14:28:22 +00001855
1856.. function:: pathconf(path, name)
1857
1858 Return system configuration information relevant to a named file. *name*
1859 specifies the configuration value to retrieve; it may be a string which is the
1860 name of a defined system value; these names are specified in a number of
1861 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1862 additional names as well. The names known to the host operating system are
1863 given in the ``pathconf_names`` dictionary. For configuration variables not
1864 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00001865
1866 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1867 specific value for *name* is not supported by the host system, even if it is
1868 included in ``pathconf_names``, an :exc:`OSError` is raised with
1869 :const:`errno.EINVAL` for the error number.
1870
Benjamin Petersonf650e462010-05-06 23:03:05 +00001871 Availability: Unix.
1872
Georg Brandl116aa622007-08-15 14:28:22 +00001873
1874.. data:: pathconf_names
1875
1876 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1877 the integer values defined for those names by the host operating system. This
1878 can be used to determine the set of names known to the system. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001879 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001880
1881
1882.. function:: readlink(path)
1883
1884 Return a string representing the path to which the symbolic link points. The
1885 result may be either an absolute or relative pathname; if it is relative, it may
1886 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1887 result)``.
1888
Georg Brandl76e55382008-10-08 16:34:57 +00001889 If the *path* is a string object, the result will also be a string object,
1890 and the call may raise an UnicodeDecodeError. If the *path* is a bytes
1891 object, the result will be a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +00001892
Brian Curtinc7395692010-07-09 15:15:09 +00001893 Availability: Unix, Windows
1894
Georg Brandlb3823372010-07-10 08:58:37 +00001895 .. versionchanged:: 3.2
1896 Added support for Windows 6.0 (Vista) symbolic links.
Georg Brandl116aa622007-08-15 14:28:22 +00001897
1898
1899.. function:: remove(path)
1900
Georg Brandla6053b42009-09-01 08:11:14 +00001901 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
1902 raised; see :func:`rmdir` below to remove a directory. This is identical to
1903 the :func:`unlink` function documented below. On Windows, attempting to
1904 remove a file that is in use causes an exception to be raised; on Unix, the
1905 directory entry is removed but the storage allocated to the file is not made
Benjamin Petersonf650e462010-05-06 23:03:05 +00001906 available until the original file is no longer in use.
1907
1908 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001909
1910
1911.. function:: removedirs(path)
1912
1913 .. index:: single: directory; deleting
1914
Christian Heimesfaf2f632008-01-06 16:59:19 +00001915 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl116aa622007-08-15 14:28:22 +00001916 leaf directory is successfully removed, :func:`removedirs` tries to
1917 successively remove every parent directory mentioned in *path* until an error
1918 is raised (which is ignored, because it generally means that a parent directory
1919 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1920 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1921 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1922 successfully removed.
1923
Georg Brandl116aa622007-08-15 14:28:22 +00001924
Benjamin Peterson799bd802011-08-31 22:15:17 -04001925.. function:: removexattr(path, attr)
1926
1927 Removes the extended filesystem attribute *attr* from *path*. *attr* should
1928 be bytes or str. If it is a string, it is encoded with the filesystem
1929 encoding.
1930
1931 Availability: Linux
1932
1933 .. versionadded:: 3.3
1934
1935
Georg Brandl116aa622007-08-15 14:28:22 +00001936.. function:: rename(src, dst)
1937
1938 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1939 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Christian Heimesfaf2f632008-01-06 16:59:19 +00001940 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl116aa622007-08-15 14:28:22 +00001941 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1942 the renaming will be an atomic operation (this is a POSIX requirement). On
1943 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01001944 file.
1945
1946 If you want cross-platform overwriting of the destination, use :func:`replace`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001947
1948 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001949
1950
1951.. function:: renames(old, new)
1952
1953 Recursive directory or file renaming function. Works like :func:`rename`, except
1954 creation of any intermediate directories needed to make the new pathname good is
1955 attempted first. After the rename, directories corresponding to rightmost path
1956 segments of the old name will be pruned away using :func:`removedirs`.
1957
Georg Brandl116aa622007-08-15 14:28:22 +00001958 .. note::
1959
1960 This function can fail with the new directory structure made if you lack
1961 permissions needed to remove the leaf directory or file.
1962
1963
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01001964.. function:: replace(src, dst)
1965
1966 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1967 :exc:`OSError` will be raised. If *dst* exists and is a file, it will
1968 be replaced silently if the user has permission. The operation may fail
1969 if *src* and *dst* are on different filesystems. If successful,
1970 the renaming will be an atomic operation (this is a POSIX requirement).
1971
1972 Availability: Unix, Windows
1973
1974 .. versionadded:: 3.3
1975
1976
Georg Brandl116aa622007-08-15 14:28:22 +00001977.. function:: rmdir(path)
1978
Georg Brandla6053b42009-09-01 08:11:14 +00001979 Remove (delete) the directory *path*. Only works when the directory is
1980 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
Benjamin Petersonf650e462010-05-06 23:03:05 +00001981 directory trees, :func:`shutil.rmtree` can be used.
1982
1983 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001984
1985
Benjamin Peterson799bd802011-08-31 22:15:17 -04001986.. data:: XATTR_SIZE_MAX
1987
1988 The maximum size the value of an extended attribute can be. Currently, this
1989 is 64 kilobytes on Linux.
1990
1991
1992.. data:: XATTR_CREATE
1993
1994 This is a possible value for the flags argument in :func:`setxattr`. It
1995 indicates the operation must create an attribute.
1996
1997
1998.. data:: XATTR_REPLACE
1999
2000 This is a possible value for the flags argument in :func:`setxattr`. It
2001 indicates the operation must replace an existing attribute.
2002
2003
2004.. function:: setxattr(path, attr, value, flags=0)
2005
2006 Set the extended filesystem attribute *attr* on *path* to *value*. *attr*
2007 must be a bytes or str with no embedded NULs. If it is str, it is encoded
2008 with the filesystem encoding. *flags* may be :data:`XATTR_REPLACE` or
2009 :data:`XATTR_CREATE`. If :data:`XATTR_REPLACE` is given and the attribute
2010 does not exist, ``EEXISTS`` will be raised. If :data:`XATTR_CREATE` is given
2011 and the attribute already exists, the attribute will not be created and
2012 ``ENODATA`` will be raised.
2013
2014 Availability: Linux
2015
2016 .. note::
2017
2018 A bug in Linux kernel versions less than 2.6.39 caused the flags argument
2019 to be ignored on some filesystems.
2020
2021 .. versionadded:: 3.3
2022
2023
Victor Stinner4195b5c2012-02-08 23:03:19 +01002024.. function:: stat(path)
Georg Brandl116aa622007-08-15 14:28:22 +00002025
R. David Murray7b1aae92011-01-24 19:34:58 +00002026 Perform the equivalent of a :c:func:`stat` system call on the given path.
2027 (This function follows symlinks; to stat a symlink use :func:`lstat`.)
Georg Brandl116aa622007-08-15 14:28:22 +00002028
Larry Hastings6fe20b32012-04-19 15:07:49 -07002029 The return value is an object whose attributes correspond roughly
2030 to the members of the :c:type:`stat` structure, namely:
R. David Murray7b1aae92011-01-24 19:34:58 +00002031
2032 * :attr:`st_mode` - protection bits,
2033 * :attr:`st_ino` - inode number,
2034 * :attr:`st_dev` - device,
2035 * :attr:`st_nlink` - number of hard links,
2036 * :attr:`st_uid` - user id of owner,
2037 * :attr:`st_gid` - group id of owner,
2038 * :attr:`st_size` - size of file, in bytes,
Larry Hastings6fe20b32012-04-19 15:07:49 -07002039 * :attr:`st_atime` - time of most recent access expressed in seconds,
2040 * :attr:`st_mtime` - time of most recent content modification
2041 expressed in seconds,
2042 * :attr:`st_ctime` - platform dependent; time of most recent metadata
2043 change on Unix, or the time of creation on Windows, expressed in seconds
2044 * :attr:`st_atime_ns` - time of most recent access
2045 expressed in nanoseconds as an integer,
2046 * :attr:`st_mtime_ns` - time of most recent content modification
2047 expressed in nanoseconds as an integer,
2048 * :attr:`st_ctime_ns` - platform dependent; time of most recent metadata
2049 change on Unix, or the time of creation on Windows,
2050 expressed in nanoseconds as an integer
Georg Brandl116aa622007-08-15 14:28:22 +00002051
2052 On some Unix systems (such as Linux), the following attributes may also be
R. David Murray7b1aae92011-01-24 19:34:58 +00002053 available:
2054
2055 * :attr:`st_blocks` - number of blocks allocated for file
2056 * :attr:`st_blksize` - filesystem blocksize
2057 * :attr:`st_rdev` - type of device if an inode device
2058 * :attr:`st_flags` - user defined flags for file
Georg Brandl116aa622007-08-15 14:28:22 +00002059
2060 On other Unix systems (such as FreeBSD), the following attributes may be
R. David Murray7b1aae92011-01-24 19:34:58 +00002061 available (but may be only filled out if root tries to use them):
2062
2063 * :attr:`st_gen` - file generation number
2064 * :attr:`st_birthtime` - time of file creation
Georg Brandl116aa622007-08-15 14:28:22 +00002065
2066 On Mac OS systems, the following attributes may also be available:
Georg Brandl116aa622007-08-15 14:28:22 +00002067
R. David Murray7b1aae92011-01-24 19:34:58 +00002068 * :attr:`st_rsize`
2069 * :attr:`st_creator`
2070 * :attr:`st_type`
Georg Brandl116aa622007-08-15 14:28:22 +00002071
2072 .. note::
2073
Senthil Kumaran3aac1792011-07-04 11:43:51 -07002074 The exact meaning and resolution of the :attr:`st_atime`,
Senthil Kumarana6bac952011-07-04 11:28:30 -07002075 :attr:`st_mtime`, and :attr:`st_ctime` attributes depend on the operating
2076 system and the file system. For example, on Windows systems using the FAT
2077 or FAT32 file systems, :attr:`st_mtime` has 2-second resolution, and
2078 :attr:`st_atime` has only 1-day resolution. See your operating system
2079 documentation for details.
Larry Hastings6fe20b32012-04-19 15:07:49 -07002080 Similarly, although :attr:`st_atime_ns`, :attr:`st_mtime_ns`,
2081 and :attr:`st_ctime_ns` are always expressed in nanoseconds, many
2082 systems do not provide nanosecond precision. On systems that do
2083 provide nanosecond precision, the floating-point object used to
2084 store :attr:`st_atime`, :attr:`st_mtime`, and :attr:`st_ctime`
2085 cannot preserve all of it, and as such will be slightly inexact.
2086 If you need the exact timestamps you should always use
2087 :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and :attr:`st_ctime_ns`.
Georg Brandl116aa622007-08-15 14:28:22 +00002088
R. David Murray7b1aae92011-01-24 19:34:58 +00002089 For backward compatibility, the return value of :func:`~os.stat` is also accessible
2090 as a tuple of at least 10 integers giving the most important (and portable)
2091 members of the :c:type:`stat` structure, in the order :attr:`st_mode`,
2092 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
2093 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
2094 :attr:`st_ctime`. More items may be added at the end by some implementations.
2095
2096 .. index:: module: stat
2097
2098 The standard module :mod:`stat` defines functions and constants that are useful
2099 for extracting information from a :c:type:`stat` structure. (On Windows, some
2100 items are filled with dummy values.)
2101
2102 Example::
2103
2104 >>> import os
2105 >>> statinfo = os.stat('somefile.txt')
2106 >>> statinfo
Raymond Hettinger8f0ae9a2011-02-18 00:53:55 +00002107 posix.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
2108 st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
2109 st_mtime=1297230027, st_ctime=1297230027)
R. David Murray7b1aae92011-01-24 19:34:58 +00002110 >>> statinfo.st_size
Raymond Hettinger8f0ae9a2011-02-18 00:53:55 +00002111 264
R. David Murray7b1aae92011-01-24 19:34:58 +00002112
Georg Brandlc575c902008-09-13 17:46:05 +00002113 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002114
Larry Hastings6fe20b32012-04-19 15:07:49 -07002115 .. versionadded:: 3.3
2116 The :attr:`st_atime_ns`, :attr:`st_mtime_ns`,
2117 and :attr:`st_ctime_ns` members.
2118
Georg Brandl116aa622007-08-15 14:28:22 +00002119
2120.. function:: stat_float_times([newvalue])
2121
2122 Determine whether :class:`stat_result` represents time stamps as float objects.
R. David Murray7b1aae92011-01-24 19:34:58 +00002123 If *newvalue* is ``True``, future calls to :func:`~os.stat` return floats, if it is
Georg Brandl116aa622007-08-15 14:28:22 +00002124 ``False``, future calls return ints. If *newvalue* is omitted, return the
2125 current setting.
2126
2127 For compatibility with older Python versions, accessing :class:`stat_result` as
2128 a tuple always returns integers.
2129
Georg Brandl55ac8f02007-09-01 13:51:09 +00002130 Python now returns float values by default. Applications which do not work
2131 correctly with floating point time stamps can use this function to restore the
2132 old behaviour.
Georg Brandl116aa622007-08-15 14:28:22 +00002133
2134 The resolution of the timestamps (that is the smallest possible fraction)
2135 depends on the system. Some systems only support second resolution; on these
2136 systems, the fraction will always be zero.
2137
2138 It is recommended that this setting is only changed at program startup time in
2139 the *__main__* module; libraries should never change this setting. If an
2140 application uses a library that works incorrectly if floating point time stamps
2141 are processed, this application should turn the feature off until the library
2142 has been corrected.
2143
2144
2145.. function:: statvfs(path)
2146
Georg Brandl60203b42010-10-06 10:11:56 +00002147 Perform a :c:func:`statvfs` system call on the given path. The return value is
Georg Brandl116aa622007-08-15 14:28:22 +00002148 an object whose attributes describe the filesystem on the given path, and
Georg Brandl60203b42010-10-06 10:11:56 +00002149 correspond to the members of the :c:type:`statvfs` structure, namely:
Georg Brandl116aa622007-08-15 14:28:22 +00002150 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
2151 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
Benjamin Petersonf650e462010-05-06 23:03:05 +00002152 :attr:`f_flag`, :attr:`f_namemax`.
2153
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +00002154 Two module-level constants are defined for the :attr:`f_flag` attribute's
2155 bit-flags: if :const:`ST_RDONLY` is set, the filesystem is mounted
2156 read-only, and if :const:`ST_NOSUID` is set, the semantics of
2157 setuid/setgid bits are disabled or not supported.
2158
2159 .. versionchanged:: 3.2
2160 The :const:`ST_RDONLY` and :const:`ST_NOSUID` constants were added.
2161
Benjamin Petersonf650e462010-05-06 23:03:05 +00002162 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002163
Georg Brandl116aa622007-08-15 14:28:22 +00002164
Benjamin Peterson5879d412009-03-30 14:51:56 +00002165.. function:: symlink(source, link_name)
Georg Brandl64a41ed2010-10-06 08:52:48 +00002166 symlink(source, link_name, target_is_directory=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002167
Brian Curtinc7395692010-07-09 15:15:09 +00002168 Create a symbolic link pointing to *source* named *link_name*.
2169
Georg Brandl64a41ed2010-10-06 08:52:48 +00002170 On Windows, symlink version takes an additional optional parameter,
2171 *target_is_directory*, which defaults to ``False``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002172
Georg Brandl64a41ed2010-10-06 08:52:48 +00002173 On Windows, a symlink represents a file or a directory, and does not morph to
Antoine Pitrou5311c1d2012-01-24 08:59:28 +01002174 the target dynamically. If *target_is_directory* is set to ``True``, the
2175 symlink will be created as a directory symlink, otherwise as a file symlink
2176 (the default).
Brian Curtind40e6f72010-07-08 21:39:08 +00002177
Georg Brandl64a41ed2010-10-06 08:52:48 +00002178 Symbolic link support was introduced in Windows 6.0 (Vista). :func:`symlink`
2179 will raise a :exc:`NotImplementedError` on Windows versions earlier than 6.0.
Brian Curtin52173d42010-12-02 18:29:18 +00002180
2181 .. note::
2182
Brian Curtin96245592010-12-28 17:08:22 +00002183 The *SeCreateSymbolicLinkPrivilege* is required in order to successfully
2184 create symlinks. This privilege is not typically granted to regular
2185 users but is available to accounts which can escalate privileges to the
2186 administrator level. Either obtaining the privilege or running your
2187 application as an administrator are ways to successfully create symlinks.
2188
Brian Curtin96245592010-12-28 17:08:22 +00002189 :exc:`OSError` is raised when the function is called by an unprivileged
2190 user.
Brian Curtind40e6f72010-07-08 21:39:08 +00002191
Georg Brandl64a41ed2010-10-06 08:52:48 +00002192 Availability: Unix, Windows.
Brian Curtinc7395692010-07-09 15:15:09 +00002193
Georg Brandlb3823372010-07-10 08:58:37 +00002194 .. versionchanged:: 3.2
2195 Added support for Windows 6.0 (Vista) symbolic links.
Georg Brandl116aa622007-08-15 14:28:22 +00002196
2197
Ross Lagerwall7807c352011-03-17 20:20:30 +02002198.. function:: sync()
2199
2200 Force write of everything to disk.
2201
2202 Availability: Unix.
2203
2204 .. versionadded:: 3.3
2205
2206
2207.. function:: truncate(path, length)
2208
2209 Truncate the file corresponding to *path*, so that it is at most
2210 *length* bytes in size.
2211
2212 Availability: Unix.
2213
2214 .. versionadded:: 3.3
2215
2216
Georg Brandl116aa622007-08-15 14:28:22 +00002217.. function:: unlink(path)
2218
Georg Brandla6053b42009-09-01 08:11:14 +00002219 Remove (delete) the file *path*. This is the same function as
2220 :func:`remove`; the :func:`unlink` name is its traditional Unix
Benjamin Petersonf650e462010-05-06 23:03:05 +00002221 name.
2222
2223 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002224
2225
Larry Hastings76ad59b2012-05-03 00:30:07 -07002226.. function:: utime(path[, times, *, ns=(atime_ns, mtime_ns)])
Georg Brandl116aa622007-08-15 14:28:22 +00002227
Larry Hastings76ad59b2012-05-03 00:30:07 -07002228 Set the access and modified times of the file specified by *path*.
2229
2230 :func:`utime` takes two optional parameters, *times* and *ns*.
2231 These specify the times set on *path* and are used as follows:
2232
2233 - If *ns* is specified,
2234 it must be a 2-tuple of the form ``(atime_ns, mtime_ns)``
2235 where each member is an int expressing nanoseconds.
2236 - If *times* is specified and is not ``None``,
2237 it must be a 2-tuple of the form ``(atime, mtime)``
2238 where each member is an int or float expressing seconds.
2239 - If *times* is specified as ``None``,
2240 this is equivalent to specifying an ``(atime, mtime)``
2241 where both times are the current time.
2242 (The effect is similar to running the Unix program
2243 :program:`touch` on *path*.)
2244 - If neither *ns* nor *times* is specified, this is
2245 equivalent to specifying *times* as ``None``.
2246
2247 Specifying both *times* and *ns* simultaneously is an error.
2248
2249 Whether a directory can be given for *path*
Brian Curtin52fbea12011-11-06 13:41:17 -06002250 depends on whether the operating system implements directories as files
2251 (for example, Windows does not). Note that the exact times you set here may
2252 not be returned by a subsequent :func:`~os.stat` call, depending on the
2253 resolution with which your operating system records access and modification
Larry Hastings76ad59b2012-05-03 00:30:07 -07002254 times; see :func:`~os.stat`. The best way to preserve exact times is to
2255 use the *st_atime_ns* and *st_mtime_ns* fields from the :func:`os.stat`
2256 result object with the *ns* parameter to `utime`.
Georg Brandl116aa622007-08-15 14:28:22 +00002257
Georg Brandlc575c902008-09-13 17:46:05 +00002258 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002259
Larry Hastings76ad59b2012-05-03 00:30:07 -07002260 .. versionadded:: 3.3
2261 The :attr:`ns` keyword parameter.
2262
Georg Brandl116aa622007-08-15 14:28:22 +00002263
Georg Brandl18244152009-09-02 20:34:52 +00002264.. function:: walk(top, topdown=True, onerror=None, followlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002265
2266 .. index::
2267 single: directory; walking
2268 single: directory; traversal
2269
Christian Heimesfaf2f632008-01-06 16:59:19 +00002270 Generate the file names in a directory tree by walking the tree
2271 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl116aa622007-08-15 14:28:22 +00002272 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
2273 filenames)``.
2274
2275 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
2276 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
2277 *filenames* is a list of the names of the non-directory files in *dirpath*.
2278 Note that the names in the lists contain no path components. To get a full path
2279 (which begins with *top*) to a file or directory in *dirpath*, do
2280 ``os.path.join(dirpath, name)``.
2281
Christian Heimesfaf2f632008-01-06 16:59:19 +00002282 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00002283 directory is generated before the triples for any of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00002284 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00002285 directory is generated after the triples for all of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00002286 (directories are generated bottom-up).
Georg Brandl116aa622007-08-15 14:28:22 +00002287
Christian Heimesfaf2f632008-01-06 16:59:19 +00002288 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl116aa622007-08-15 14:28:22 +00002289 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
2290 recurse into the subdirectories whose names remain in *dirnames*; this can be
2291 used to prune the search, impose a specific order of visiting, or even to inform
2292 :func:`walk` about directories the caller creates or renames before it resumes
Christian Heimesfaf2f632008-01-06 16:59:19 +00002293 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl116aa622007-08-15 14:28:22 +00002294 ineffective, because in bottom-up mode the directories in *dirnames* are
2295 generated before *dirpath* itself is generated.
2296
Ezio Melotti67494f22011-10-18 12:59:39 +03002297 By default, errors from the :func:`listdir` call are ignored. If optional
Georg Brandl116aa622007-08-15 14:28:22 +00002298 argument *onerror* is specified, it should be a function; it will be called with
2299 one argument, an :exc:`OSError` instance. It can report the error to continue
2300 with the walk, or raise the exception to abort the walk. Note that the filename
2301 is available as the ``filename`` attribute of the exception object.
2302
2303 By default, :func:`walk` will not walk down into symbolic links that resolve to
Christian Heimesfaf2f632008-01-06 16:59:19 +00002304 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl116aa622007-08-15 14:28:22 +00002305 symlinks, on systems that support them.
2306
Georg Brandl116aa622007-08-15 14:28:22 +00002307 .. note::
2308
Christian Heimesfaf2f632008-01-06 16:59:19 +00002309 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl116aa622007-08-15 14:28:22 +00002310 link points to a parent directory of itself. :func:`walk` does not keep track of
2311 the directories it visited already.
2312
2313 .. note::
2314
2315 If you pass a relative pathname, don't change the current working directory
2316 between resumptions of :func:`walk`. :func:`walk` never changes the current
2317 directory, and assumes that its caller doesn't either.
2318
2319 This example displays the number of bytes taken by non-directory files in each
2320 directory under the starting directory, except that it doesn't look under any
2321 CVS subdirectory::
2322
2323 import os
2324 from os.path import join, getsize
2325 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00002326 print(root, "consumes", end=" ")
2327 print(sum(getsize(join(root, name)) for name in files), end=" ")
2328 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00002329 if 'CVS' in dirs:
2330 dirs.remove('CVS') # don't visit CVS directories
2331
Christian Heimesfaf2f632008-01-06 16:59:19 +00002332 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl116aa622007-08-15 14:28:22 +00002333 doesn't allow deleting a directory before the directory is empty::
2334
Christian Heimesfaf2f632008-01-06 16:59:19 +00002335 # Delete everything reachable from the directory named in "top",
Georg Brandl116aa622007-08-15 14:28:22 +00002336 # assuming there are no symbolic links.
2337 # CAUTION: This is dangerous! For example, if top == '/', it
2338 # could delete all your disk files.
2339 import os
2340 for root, dirs, files in os.walk(top, topdown=False):
2341 for name in files:
2342 os.remove(os.path.join(root, name))
2343 for name in dirs:
2344 os.rmdir(os.path.join(root, name))
2345
Georg Brandl116aa622007-08-15 14:28:22 +00002346
Charles-François Natali7372b062012-02-05 15:15:38 +01002347.. function:: fwalk(top, topdown=True, onerror=None, followlinks=False)
2348
2349 .. index::
2350 single: directory; walking
2351 single: directory; traversal
2352
Eli Benderskyd049d5c2012-02-11 09:52:29 +02002353 This behaves exactly like :func:`walk`, except that it yields a 4-tuple
2354 ``(dirpath, dirnames, filenames, dirfd)``.
Charles-François Natali7372b062012-02-05 15:15:38 +01002355
2356 *dirpath*, *dirnames* and *filenames* are identical to :func:`walk` output,
2357 and *dirfd* is a file descriptor referring to the directory *dirpath*.
2358
2359 .. note::
2360
2361 Since :func:`fwalk` yields file descriptors, those are only valid until
2362 the next iteration step, so you should duplicate them (e.g. with
2363 :func:`dup`) if you want to keep them longer.
2364
2365 This example displays the number of bytes taken by non-directory files in each
2366 directory under the starting directory, except that it doesn't look under any
2367 CVS subdirectory::
2368
2369 import os
2370 for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
2371 print(root, "consumes", end="")
2372 print(sum([os.fstatat(rootfd, name).st_size for name in files]),
2373 end="")
2374 print("bytes in", len(files), "non-directory files")
2375 if 'CVS' in dirs:
2376 dirs.remove('CVS') # don't visit CVS directories
2377
2378 In the next example, walking the tree bottom-up is essential:
2379 :func:`unlinkat` doesn't allow deleting a directory before the directory is
2380 empty::
2381
2382 # Delete everything reachable from the directory named in "top",
2383 # assuming there are no symbolic links.
2384 # CAUTION: This is dangerous! For example, if top == '/', it
2385 # could delete all your disk files.
2386 import os
2387 for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
2388 for name in files:
2389 os.unlinkat(rootfd, name)
2390 for name in dirs:
2391 os.unlinkat(rootfd, name, os.AT_REMOVEDIR)
2392
2393 Availability: Unix.
2394
2395 .. versionadded:: 3.3
2396
2397
Georg Brandl116aa622007-08-15 14:28:22 +00002398.. _os-process:
2399
2400Process Management
2401------------------
2402
2403These functions may be used to create and manage processes.
2404
2405The various :func:`exec\*` functions take a list of arguments for the new
2406program loaded into the process. In each case, the first of these arguments is
2407passed to the new program as its own name rather than as an argument a user may
2408have typed on a command line. For the C programmer, this is the ``argv[0]``
Georg Brandl60203b42010-10-06 10:11:56 +00002409passed to a program's :c:func:`main`. For example, ``os.execv('/bin/echo',
Georg Brandl116aa622007-08-15 14:28:22 +00002410['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
2411to be ignored.
2412
2413
2414.. function:: abort()
2415
2416 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
2417 behavior is to produce a core dump; on Windows, the process immediately returns
Victor Stinner6e2e3b92011-07-08 02:26:39 +02002418 an exit code of ``3``. Be aware that calling this function will not call the
2419 Python signal handler registered for :const:`SIGABRT` with
2420 :func:`signal.signal`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002421
Georg Brandlc575c902008-09-13 17:46:05 +00002422 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002423
2424
2425.. function:: execl(path, arg0, arg1, ...)
2426 execle(path, arg0, arg1, ..., env)
2427 execlp(file, arg0, arg1, ...)
2428 execlpe(file, arg0, arg1, ..., env)
2429 execv(path, args)
2430 execve(path, args, env)
2431 execvp(file, args)
2432 execvpe(file, args, env)
2433
2434 These functions all execute a new program, replacing the current process; they
2435 do not return. On Unix, the new executable is loaded into the current process,
Christian Heimesfaf2f632008-01-06 16:59:19 +00002436 and will have the same process id as the caller. Errors will be reported as
Georg Brandl48310cd2009-01-03 21:18:54 +00002437 :exc:`OSError` exceptions.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002438
2439 The current process is replaced immediately. Open file objects and
2440 descriptors are not flushed, so if there may be data buffered
2441 on these open files, you should flush them using
2442 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
2443 :func:`exec\*` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002444
Christian Heimesfaf2f632008-01-06 16:59:19 +00002445 The "l" and "v" variants of the :func:`exec\*` functions differ in how
2446 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00002447 to work with if the number of parameters is fixed when the code is written; the
2448 individual parameters simply become additional parameters to the :func:`execl\*`
Christian Heimesfaf2f632008-01-06 16:59:19 +00002449 functions. The "v" variants are good when the number of parameters is
Georg Brandl116aa622007-08-15 14:28:22 +00002450 variable, with the arguments being passed in a list or tuple as the *args*
2451 parameter. In either case, the arguments to the child process should start with
2452 the name of the command being run, but this is not enforced.
2453
Christian Heimesfaf2f632008-01-06 16:59:19 +00002454 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00002455 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
2456 :envvar:`PATH` environment variable to locate the program *file*. When the
2457 environment is being replaced (using one of the :func:`exec\*e` variants,
2458 discussed in the next paragraph), the new environment is used as the source of
2459 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
2460 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
2461 locate the executable; *path* must contain an appropriate absolute or relative
2462 path.
2463
2464 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Christian Heimesfaf2f632008-01-06 16:59:19 +00002465 that these all end in "e"), the *env* parameter must be a mapping which is
Christian Heimesa342c012008-04-20 21:01:16 +00002466 used to define the environment variables for the new process (these are used
2467 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl116aa622007-08-15 14:28:22 +00002468 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
Georg Brandl48310cd2009-01-03 21:18:54 +00002469 inherit the environment of the current process.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002470
2471 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002472
2473
2474.. function:: _exit(n)
2475
Georg Brandl6f4e68d2010-10-17 10:51:45 +00002476 Exit the process with status *n*, without calling cleanup handlers, flushing
Benjamin Petersonf650e462010-05-06 23:03:05 +00002477 stdio buffers, etc.
2478
2479 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002480
2481 .. note::
2482
Georg Brandl6f4e68d2010-10-17 10:51:45 +00002483 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should
2484 normally only be used in the child process after a :func:`fork`.
Georg Brandl116aa622007-08-15 14:28:22 +00002485
Christian Heimesfaf2f632008-01-06 16:59:19 +00002486The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl116aa622007-08-15 14:28:22 +00002487although they are not required. These are typically used for system programs
2488written in Python, such as a mail server's external command delivery program.
2489
2490.. note::
2491
2492 Some of these may not be available on all Unix platforms, since there is some
2493 variation. These constants are defined where they are defined by the underlying
2494 platform.
2495
2496
2497.. data:: EX_OK
2498
Benjamin Petersonf650e462010-05-06 23:03:05 +00002499 Exit code that means no error occurred.
2500
2501 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002502
Georg Brandl116aa622007-08-15 14:28:22 +00002503
2504.. data:: EX_USAGE
2505
2506 Exit code that means the command was used incorrectly, such as when the wrong
Benjamin Petersonf650e462010-05-06 23:03:05 +00002507 number of arguments are given.
2508
2509 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002510
Georg Brandl116aa622007-08-15 14:28:22 +00002511
2512.. data:: EX_DATAERR
2513
Benjamin Petersonf650e462010-05-06 23:03:05 +00002514 Exit code that means the input data was incorrect.
2515
2516 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002517
Georg Brandl116aa622007-08-15 14:28:22 +00002518
2519.. data:: EX_NOINPUT
2520
2521 Exit code that means an input file did not exist or was not readable.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002522
Georg Brandlc575c902008-09-13 17:46:05 +00002523 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002524
Georg Brandl116aa622007-08-15 14:28:22 +00002525
2526.. data:: EX_NOUSER
2527
Benjamin Petersonf650e462010-05-06 23:03:05 +00002528 Exit code that means a specified user did not exist.
2529
2530 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002531
Georg Brandl116aa622007-08-15 14:28:22 +00002532
2533.. data:: EX_NOHOST
2534
Benjamin Petersonf650e462010-05-06 23:03:05 +00002535 Exit code that means a specified host did not exist.
2536
2537 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002538
Georg Brandl116aa622007-08-15 14:28:22 +00002539
2540.. data:: EX_UNAVAILABLE
2541
Benjamin Petersonf650e462010-05-06 23:03:05 +00002542 Exit code that means that a required service is unavailable.
2543
2544 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002545
Georg Brandl116aa622007-08-15 14:28:22 +00002546
2547.. data:: EX_SOFTWARE
2548
Benjamin Petersonf650e462010-05-06 23:03:05 +00002549 Exit code that means an internal software error was detected.
2550
2551 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002552
Georg Brandl116aa622007-08-15 14:28:22 +00002553
2554.. data:: EX_OSERR
2555
2556 Exit code that means an operating system error was detected, such as the
Benjamin Petersonf650e462010-05-06 23:03:05 +00002557 inability to fork or create a pipe.
2558
2559 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002560
Georg Brandl116aa622007-08-15 14:28:22 +00002561
2562.. data:: EX_OSFILE
2563
2564 Exit code that means some system file did not exist, could not be opened, or had
Benjamin Petersonf650e462010-05-06 23:03:05 +00002565 some other kind of error.
2566
2567 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002568
Georg Brandl116aa622007-08-15 14:28:22 +00002569
2570.. data:: EX_CANTCREAT
2571
2572 Exit code that means a user specified output file could not be created.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002573
Georg Brandlc575c902008-09-13 17:46:05 +00002574 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002575
Georg Brandl116aa622007-08-15 14:28:22 +00002576
2577.. data:: EX_IOERR
2578
2579 Exit code that means that an error occurred while doing I/O on some file.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002580
Georg Brandlc575c902008-09-13 17:46:05 +00002581 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002582
Georg Brandl116aa622007-08-15 14:28:22 +00002583
2584.. data:: EX_TEMPFAIL
2585
2586 Exit code that means a temporary failure occurred. This indicates something
2587 that may not really be an error, such as a network connection that couldn't be
Benjamin Petersonf650e462010-05-06 23:03:05 +00002588 made during a retryable operation.
2589
2590 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002591
Georg Brandl116aa622007-08-15 14:28:22 +00002592
2593.. data:: EX_PROTOCOL
2594
2595 Exit code that means that a protocol exchange was illegal, invalid, or not
Benjamin Petersonf650e462010-05-06 23:03:05 +00002596 understood.
2597
2598 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002599
Georg Brandl116aa622007-08-15 14:28:22 +00002600
2601.. data:: EX_NOPERM
2602
2603 Exit code that means that there were insufficient permissions to perform the
Benjamin Petersonf650e462010-05-06 23:03:05 +00002604 operation (but not intended for file system problems).
2605
2606 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002607
Georg Brandl116aa622007-08-15 14:28:22 +00002608
2609.. data:: EX_CONFIG
2610
2611 Exit code that means that some kind of configuration error occurred.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002612
Georg Brandlc575c902008-09-13 17:46:05 +00002613 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002614
Georg Brandl116aa622007-08-15 14:28:22 +00002615
2616.. data:: EX_NOTFOUND
2617
Benjamin Petersonf650e462010-05-06 23:03:05 +00002618 Exit code that means something like "an entry was not found".
2619
2620 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002621
Georg Brandl116aa622007-08-15 14:28:22 +00002622
2623.. function:: fork()
2624
Christian Heimesfaf2f632008-01-06 16:59:19 +00002625 Fork a child process. Return ``0`` in the child and the child's process id in the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002626 parent. If an error occurs :exc:`OSError` is raised.
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +00002627
2628 Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
2629 known issues when using fork() from a thread.
2630
Georg Brandlc575c902008-09-13 17:46:05 +00002631 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002632
2633
2634.. function:: forkpty()
2635
2636 Fork a child process, using a new pseudo-terminal as the child's controlling
2637 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
2638 new child's process id in the parent, and *fd* is the file descriptor of the
2639 master end of the pseudo-terminal. For a more portable approach, use the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002640 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002641
Georg Brandlc575c902008-09-13 17:46:05 +00002642 Availability: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002643
2644
2645.. function:: kill(pid, sig)
2646
2647 .. index::
2648 single: process; killing
2649 single: process; signalling
2650
2651 Send signal *sig* to the process *pid*. Constants for the specific signals
2652 available on the host platform are defined in the :mod:`signal` module.
Brian Curtineb24d742010-04-12 17:16:38 +00002653
2654 Windows: The :data:`signal.CTRL_C_EVENT` and
2655 :data:`signal.CTRL_BREAK_EVENT` signals are special signals which can
2656 only be sent to console processes which share a common console window,
2657 e.g., some subprocesses. Any other value for *sig* will cause the process
2658 to be unconditionally killed by the TerminateProcess API, and the exit code
2659 will be set to *sig*. The Windows version of :func:`kill` additionally takes
2660 process handles to be killed.
Georg Brandl116aa622007-08-15 14:28:22 +00002661
Victor Stinnerb3e72192011-05-08 01:46:11 +02002662 See also :func:`signal.pthread_kill`.
2663
Georg Brandl67b21b72010-08-17 15:07:14 +00002664 .. versionadded:: 3.2
2665 Windows support.
Brian Curtin904bd392010-04-20 15:28:06 +00002666
Georg Brandl116aa622007-08-15 14:28:22 +00002667
2668.. function:: killpg(pgid, sig)
2669
2670 .. index::
2671 single: process; killing
2672 single: process; signalling
2673
Benjamin Petersonf650e462010-05-06 23:03:05 +00002674 Send the signal *sig* to the process group *pgid*.
2675
2676 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002677
Georg Brandl116aa622007-08-15 14:28:22 +00002678
2679.. function:: nice(increment)
2680
2681 Add *increment* to the process's "niceness". Return the new niceness.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002682
Georg Brandlc575c902008-09-13 17:46:05 +00002683 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002684
2685
2686.. function:: plock(op)
2687
2688 Lock program segments into memory. The value of *op* (defined in
Benjamin Petersonf650e462010-05-06 23:03:05 +00002689 ``<sys/lock.h>``) determines which segments are locked.
2690
2691 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002692
2693
2694.. function:: popen(...)
2695 :noindex:
2696
2697 Run child processes, returning opened pipes for communications. These functions
2698 are described in section :ref:`os-newstreams`.
2699
2700
2701.. function:: spawnl(mode, path, ...)
2702 spawnle(mode, path, ..., env)
2703 spawnlp(mode, file, ...)
2704 spawnlpe(mode, file, ..., env)
2705 spawnv(mode, path, args)
2706 spawnve(mode, path, args, env)
2707 spawnvp(mode, file, args)
2708 spawnvpe(mode, file, args, env)
2709
2710 Execute the program *path* in a new process.
2711
2712 (Note that the :mod:`subprocess` module provides more powerful facilities for
2713 spawning new processes and retrieving their results; using that module is
Benjamin Peterson87c8d872009-06-11 22:54:11 +00002714 preferable to using these functions. Check especially the
2715 :ref:`subprocess-replacements` section.)
Georg Brandl116aa622007-08-15 14:28:22 +00002716
Christian Heimesfaf2f632008-01-06 16:59:19 +00002717 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl116aa622007-08-15 14:28:22 +00002718 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
2719 exits normally, or ``-signal``, where *signal* is the signal that killed the
Christian Heimesfaf2f632008-01-06 16:59:19 +00002720 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl116aa622007-08-15 14:28:22 +00002721 be used with the :func:`waitpid` function.
2722
Christian Heimesfaf2f632008-01-06 16:59:19 +00002723 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
2724 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00002725 to work with if the number of parameters is fixed when the code is written; the
2726 individual parameters simply become additional parameters to the
Christian Heimesfaf2f632008-01-06 16:59:19 +00002727 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl116aa622007-08-15 14:28:22 +00002728 parameters is variable, with the arguments being passed in a list or tuple as
2729 the *args* parameter. In either case, the arguments to the child process must
2730 start with the name of the command being run.
2731
Christian Heimesfaf2f632008-01-06 16:59:19 +00002732 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00002733 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
2734 :envvar:`PATH` environment variable to locate the program *file*. When the
2735 environment is being replaced (using one of the :func:`spawn\*e` variants,
2736 discussed in the next paragraph), the new environment is used as the source of
2737 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
2738 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
2739 :envvar:`PATH` variable to locate the executable; *path* must contain an
2740 appropriate absolute or relative path.
2741
2742 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Christian Heimesfaf2f632008-01-06 16:59:19 +00002743 (note that these all end in "e"), the *env* parameter must be a mapping
Christian Heimesa342c012008-04-20 21:01:16 +00002744 which is used to define the environment variables for the new process (they are
2745 used instead of the current process' environment); the functions
Georg Brandl116aa622007-08-15 14:28:22 +00002746 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
Benjamin Petersond23f8222009-04-05 19:13:16 +00002747 the new process to inherit the environment of the current process. Note that
2748 keys and values in the *env* dictionary must be strings; invalid keys or
2749 values will cause the function to fail, with a return value of ``127``.
Georg Brandl116aa622007-08-15 14:28:22 +00002750
2751 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
2752 equivalent::
2753
2754 import os
2755 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
2756
2757 L = ['cp', 'index.html', '/dev/null']
2758 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
2759
2760 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
Antoine Pitrou0e752dd2011-07-19 01:26:58 +02002761 and :func:`spawnvpe` are not available on Windows. :func:`spawnle` and
2762 :func:`spawnve` are not thread-safe on Windows; we advise you to use the
2763 :mod:`subprocess` module instead.
Georg Brandl116aa622007-08-15 14:28:22 +00002764
Georg Brandl116aa622007-08-15 14:28:22 +00002765
2766.. data:: P_NOWAIT
2767 P_NOWAITO
2768
2769 Possible values for the *mode* parameter to the :func:`spawn\*` family of
2770 functions. If either of these values is given, the :func:`spawn\*` functions
Christian Heimesfaf2f632008-01-06 16:59:19 +00002771 will return as soon as the new process has been created, with the process id as
Benjamin Petersonf650e462010-05-06 23:03:05 +00002772 the return value.
2773
2774 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002775
Georg Brandl116aa622007-08-15 14:28:22 +00002776
2777.. data:: P_WAIT
2778
2779 Possible value for the *mode* parameter to the :func:`spawn\*` family of
2780 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
2781 return until the new process has run to completion and will return the exit code
2782 of the process the run is successful, or ``-signal`` if a signal kills the
Benjamin Petersonf650e462010-05-06 23:03:05 +00002783 process.
2784
2785 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002786
Georg Brandl116aa622007-08-15 14:28:22 +00002787
2788.. data:: P_DETACH
2789 P_OVERLAY
2790
2791 Possible values for the *mode* parameter to the :func:`spawn\*` family of
2792 functions. These are less portable than those listed above. :const:`P_DETACH`
2793 is similar to :const:`P_NOWAIT`, but the new process is detached from the
2794 console of the calling process. If :const:`P_OVERLAY` is used, the current
2795 process will be replaced; the :func:`spawn\*` function will not return.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002796
Georg Brandl116aa622007-08-15 14:28:22 +00002797 Availability: Windows.
2798
Georg Brandl116aa622007-08-15 14:28:22 +00002799
2800.. function:: startfile(path[, operation])
2801
2802 Start a file with its associated application.
2803
2804 When *operation* is not specified or ``'open'``, this acts like double-clicking
2805 the file in Windows Explorer, or giving the file name as an argument to the
2806 :program:`start` command from the interactive command shell: the file is opened
2807 with whatever application (if any) its extension is associated.
2808
2809 When another *operation* is given, it must be a "command verb" that specifies
2810 what should be done with the file. Common verbs documented by Microsoft are
2811 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
2812 ``'find'`` (to be used on directories).
2813
2814 :func:`startfile` returns as soon as the associated application is launched.
2815 There is no option to wait for the application to close, and no way to retrieve
2816 the application's exit status. The *path* parameter is relative to the current
2817 directory. If you want to use an absolute path, make sure the first character
Georg Brandl60203b42010-10-06 10:11:56 +00002818 is not a slash (``'/'``); the underlying Win32 :c:func:`ShellExecute` function
Georg Brandl116aa622007-08-15 14:28:22 +00002819 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
Benjamin Petersonf650e462010-05-06 23:03:05 +00002820 the path is properly encoded for Win32.
2821
2822 Availability: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00002823
Georg Brandl116aa622007-08-15 14:28:22 +00002824
2825.. function:: system(command)
2826
2827 Execute the command (a string) in a subshell. This is implemented by calling
Georg Brandl60203b42010-10-06 10:11:56 +00002828 the Standard C function :c:func:`system`, and has the same limitations.
Georg Brandl8f7b4272010-10-14 06:35:53 +00002829 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of
2830 the executed command. If *command* generates any output, it will be sent to
2831 the interpreter standard output stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002832
2833 On Unix, the return value is the exit status of the process encoded in the
Georg Brandl8f7b4272010-10-14 06:35:53 +00002834 format specified for :func:`wait`. Note that POSIX does not specify the
2835 meaning of the return value of the C :c:func:`system` function, so the return
2836 value of the Python function is system-dependent.
Georg Brandl116aa622007-08-15 14:28:22 +00002837
Georg Brandl8f7b4272010-10-14 06:35:53 +00002838 On Windows, the return value is that returned by the system shell after
2839 running *command*. The shell is given by the Windows environment variable
2840 :envvar:`COMSPEC`: it is usually :program:`cmd.exe`, which returns the exit
2841 status of the command run; on systems using a non-native shell, consult your
2842 shell documentation.
Georg Brandl116aa622007-08-15 14:28:22 +00002843
Georg Brandl8f7b4272010-10-14 06:35:53 +00002844 The :mod:`subprocess` module provides more powerful facilities for spawning
2845 new processes and retrieving their results; using that module is preferable
2846 to using this function. See the :ref:`subprocess-replacements` section in
2847 the :mod:`subprocess` documentation for some helpful recipes.
Georg Brandl116aa622007-08-15 14:28:22 +00002848
Benjamin Petersonf650e462010-05-06 23:03:05 +00002849 Availability: Unix, Windows.
2850
Georg Brandl116aa622007-08-15 14:28:22 +00002851
2852.. function:: times()
2853
Benjamin Petersonf650e462010-05-06 23:03:05 +00002854 Return a 5-tuple of floating point numbers indicating accumulated (processor
2855 or other) times, in seconds. The items are: user time, system time,
2856 children's user time, children's system time, and elapsed real time since a
2857 fixed point in the past, in that order. See the Unix manual page
2858 :manpage:`times(2)` or the corresponding Windows Platform API documentation.
2859 On Windows, only the first two items are filled, the others are zero.
2860
2861 Availability: Unix, Windows
Georg Brandl116aa622007-08-15 14:28:22 +00002862
2863
2864.. function:: wait()
2865
2866 Wait for completion of a child process, and return a tuple containing its pid
2867 and exit status indication: a 16-bit number, whose low byte is the signal number
2868 that killed the process, and whose high byte is the exit status (if the signal
2869 number is zero); the high bit of the low byte is set if a core file was
Benjamin Petersonf650e462010-05-06 23:03:05 +00002870 produced.
2871
2872 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002873
Ross Lagerwall7807c352011-03-17 20:20:30 +02002874.. function:: waitid(idtype, id, options)
2875
2876 Wait for the completion of one or more child processes.
2877 *idtype* can be :data:`P_PID`, :data:`P_PGID` or :data:`P_ALL`.
2878 *id* specifies the pid to wait on.
2879 *options* is constructed from the ORing of one or more of :data:`WEXITED`,
2880 :data:`WSTOPPED` or :data:`WCONTINUED` and additionally may be ORed with
2881 :data:`WNOHANG` or :data:`WNOWAIT`. The return value is an object
2882 representing the data contained in the :c:type:`siginfo_t` structure, namely:
2883 :attr:`si_pid`, :attr:`si_uid`, :attr:`si_signo`, :attr:`si_status`,
2884 :attr:`si_code` or ``None`` if :data:`WNOHANG` is specified and there are no
2885 children in a waitable state.
2886
2887 Availability: Unix.
2888
2889 .. versionadded:: 3.3
2890
2891.. data:: P_PID
2892 P_PGID
2893 P_ALL
2894
2895 These are the possible values for *idtype* in :func:`waitid`. They affect
2896 how *id* is interpreted.
2897
2898 Availability: Unix.
2899
2900 .. versionadded:: 3.3
2901
2902.. data:: WEXITED
2903 WSTOPPED
2904 WNOWAIT
2905
2906 Flags that can be used in *options* in :func:`waitid` that specify what
2907 child signal to wait for.
2908
2909 Availability: Unix.
2910
2911 .. versionadded:: 3.3
2912
2913
2914.. data:: CLD_EXITED
2915 CLD_DUMPED
2916 CLD_TRAPPED
2917 CLD_CONTINUED
2918
2919 These are the possible values for :attr:`si_code` in the result returned by
2920 :func:`waitid`.
2921
2922 Availability: Unix.
2923
2924 .. versionadded:: 3.3
2925
Georg Brandl116aa622007-08-15 14:28:22 +00002926
2927.. function:: waitpid(pid, options)
2928
2929 The details of this function differ on Unix and Windows.
2930
2931 On Unix: Wait for completion of a child process given by process id *pid*, and
2932 return a tuple containing its process id and exit status indication (encoded as
2933 for :func:`wait`). The semantics of the call are affected by the value of the
2934 integer *options*, which should be ``0`` for normal operation.
2935
2936 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
2937 that specific process. If *pid* is ``0``, the request is for the status of any
2938 child in the process group of the current process. If *pid* is ``-1``, the
2939 request pertains to any child of the current process. If *pid* is less than
2940 ``-1``, status is requested for any process in the process group ``-pid`` (the
2941 absolute value of *pid*).
2942
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00002943 An :exc:`OSError` is raised with the value of errno when the syscall
2944 returns -1.
2945
Georg Brandl116aa622007-08-15 14:28:22 +00002946 On Windows: Wait for completion of a process given by process handle *pid*, and
2947 return a tuple containing *pid*, and its exit status shifted left by 8 bits
2948 (shifting makes cross-platform use of the function easier). A *pid* less than or
2949 equal to ``0`` has no special meaning on Windows, and raises an exception. The
2950 value of integer *options* has no effect. *pid* can refer to any process whose
2951 id is known, not necessarily a child process. The :func:`spawn` functions called
2952 with :const:`P_NOWAIT` return suitable process handles.
2953
2954
Victor Stinner4195b5c2012-02-08 23:03:19 +01002955.. function:: wait3([options])
Georg Brandl116aa622007-08-15 14:28:22 +00002956
2957 Similar to :func:`waitpid`, except no process id argument is given and a
2958 3-element tuple containing the child's process id, exit status indication, and
2959 resource usage information is returned. Refer to :mod:`resource`.\
2960 :func:`getrusage` for details on resource usage information. The option
2961 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002962
Georg Brandl116aa622007-08-15 14:28:22 +00002963 Availability: Unix.
2964
Georg Brandl116aa622007-08-15 14:28:22 +00002965
Victor Stinner4195b5c2012-02-08 23:03:19 +01002966.. function:: wait4(pid, options)
Georg Brandl116aa622007-08-15 14:28:22 +00002967
2968 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
2969 process id, exit status indication, and resource usage information is returned.
2970 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
2971 information. The arguments to :func:`wait4` are the same as those provided to
Benjamin Petersonf650e462010-05-06 23:03:05 +00002972 :func:`waitpid`.
2973
2974 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002975
Georg Brandl116aa622007-08-15 14:28:22 +00002976
2977.. data:: WNOHANG
2978
2979 The option for :func:`waitpid` to return immediately if no child process status
2980 is available immediately. The function returns ``(0, 0)`` in this case.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002981
Georg Brandlc575c902008-09-13 17:46:05 +00002982 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002983
2984
2985.. data:: WCONTINUED
2986
2987 This option causes child processes to be reported if they have been continued
Benjamin Petersonf650e462010-05-06 23:03:05 +00002988 from a job control stop since their status was last reported.
2989
2990 Availability: Some Unix systems.
Georg Brandl116aa622007-08-15 14:28:22 +00002991
Georg Brandl116aa622007-08-15 14:28:22 +00002992
2993.. data:: WUNTRACED
2994
2995 This option causes child processes to be reported if they have been stopped but
Benjamin Petersonf650e462010-05-06 23:03:05 +00002996 their current state has not been reported since they were stopped.
2997
2998 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002999
Georg Brandl116aa622007-08-15 14:28:22 +00003000
3001The following functions take a process status code as returned by
3002:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
3003used to determine the disposition of a process.
3004
Georg Brandl116aa622007-08-15 14:28:22 +00003005.. function:: WCOREDUMP(status)
3006
Christian Heimesfaf2f632008-01-06 16:59:19 +00003007 Return ``True`` if a core dump was generated for the process, otherwise
Benjamin Petersonf650e462010-05-06 23:03:05 +00003008 return ``False``.
3009
3010 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003011
Georg Brandl116aa622007-08-15 14:28:22 +00003012
3013.. function:: WIFCONTINUED(status)
3014
Christian Heimesfaf2f632008-01-06 16:59:19 +00003015 Return ``True`` if the process has been continued from a job control stop,
Benjamin Petersonf650e462010-05-06 23:03:05 +00003016 otherwise return ``False``.
3017
3018 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003019
Georg Brandl116aa622007-08-15 14:28:22 +00003020
3021.. function:: WIFSTOPPED(status)
3022
Christian Heimesfaf2f632008-01-06 16:59:19 +00003023 Return ``True`` if the process has been stopped, otherwise return
Benjamin Petersonf650e462010-05-06 23:03:05 +00003024 ``False``.
3025
3026 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003027
3028
3029.. function:: WIFSIGNALED(status)
3030
Christian Heimesfaf2f632008-01-06 16:59:19 +00003031 Return ``True`` if the process exited due to a signal, otherwise return
Benjamin Petersonf650e462010-05-06 23:03:05 +00003032 ``False``.
3033
3034 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003035
3036
3037.. function:: WIFEXITED(status)
3038
Christian Heimesfaf2f632008-01-06 16:59:19 +00003039 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
Benjamin Petersonf650e462010-05-06 23:03:05 +00003040 otherwise return ``False``.
3041
3042 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003043
3044
3045.. function:: WEXITSTATUS(status)
3046
3047 If ``WIFEXITED(status)`` is true, return the integer parameter to the
3048 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003049
Georg Brandlc575c902008-09-13 17:46:05 +00003050 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003051
3052
3053.. function:: WSTOPSIG(status)
3054
Benjamin Petersonf650e462010-05-06 23:03:05 +00003055 Return the signal which caused the process to stop.
3056
3057 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003058
3059
3060.. function:: WTERMSIG(status)
3061
Benjamin Petersonf650e462010-05-06 23:03:05 +00003062 Return the signal which caused the process to exit.
3063
3064 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003065
3066
Benjamin Peterson94b580d2011-08-02 17:30:04 -05003067Interface to the scheduler
3068--------------------------
3069
3070These functions control how a process is allocated CPU time by the operating
3071system. They are only available on some Unix platforms. For more detailed
3072information, consult your Unix manpages.
3073
3074.. versionadded:: 3.3
3075
3076The following scheduling policies are exposed if they are a supported by the
3077operating system.
3078
3079.. data:: SCHED_OTHER
3080
3081 The default scheduling policy.
3082
3083.. data:: SCHED_BATCH
3084
3085 Scheduling policy for CPU-intensive processes that tries to preserve
3086 interactivity on the rest of the computer.
3087
3088.. data:: SCHED_IDLE
3089
3090 Scheduling policy for extremely low priority background tasks.
3091
3092.. data:: SCHED_SPORADIC
3093
3094 Scheduling policy for sporadic server programs.
3095
3096.. data:: SCHED_FIFO
3097
3098 A First In First Out scheduling policy.
3099
3100.. data:: SCHED_RR
3101
3102 A round-robin scheduling policy.
3103
3104.. data:: SCHED_RESET_ON_FORK
3105
3106 This flag can OR'ed with any other scheduling policy. When a process with
3107 this flag set forks, its child's scheduling policy and priority are reset to
3108 the default.
3109
3110
3111.. class:: sched_param(sched_priority)
3112
3113 This class represents tunable scheduling parameters used in
3114 :func:`sched_setparam`, :func:`sched_setscheduler`, and
3115 :func:`sched_getparam`. It is immutable.
3116
3117 At the moment, there is only one possible parameter:
3118
3119 .. attribute:: sched_priority
3120
3121 The scheduling priority for a scheduling policy.
3122
3123
3124.. function:: sched_get_priority_min(policy)
3125
3126 Get the minimum priority value for *policy*. *policy* is one of the
3127 scheduling policy constants above.
3128
3129
3130.. function:: sched_get_priority_max(policy)
3131
3132 Get the maximum priority value for *policy*. *policy* is one of the
3133 scheduling policy constants above.
3134
3135
3136.. function:: sched_setscheduler(pid, policy, param)
3137
3138 Set the scheduling policy for the process with PID *pid*. A *pid* of 0 means
3139 the calling process. *policy* is one of the scheduling policy constants
3140 above. *param* is a :class:`sched_param` instance.
3141
3142
3143.. function:: sched_getscheduler(pid)
3144
3145 Return the scheduling policy for the process with PID *pid*. A *pid* of 0
3146 means the calling process. The result is one of the scheduling policy
3147 constants above.
3148
3149
3150.. function:: sched_setparam(pid, param)
3151
3152 Set a scheduling parameters for the process with PID *pid*. A *pid* of 0 means
3153 the calling process. *param* is a :class:`sched_param` instance.
3154
3155
3156.. function:: sched_getparam(pid)
3157
3158 Return the scheduling parameters as a :class:`sched_param` instance for the
3159 process with PID *pid*. A *pid* of 0 means the calling process.
3160
3161
3162.. function:: sched_rr_get_interval(pid)
3163
3164 Return the round-robin quantum in seconds for the process with PID *pid*. A
3165 *pid* of 0 means the calling process.
3166
3167
3168.. function:: sched_yield()
3169
3170 Voluntarily relinquish the CPU.
3171
3172
3173.. class:: cpu_set(ncpus)
3174
3175 :class:`cpu_set` represents a set of CPUs on which a process is eligible to
3176 run. *ncpus* is the number of CPUs the set should describe. Methods on
3177 :class:`cpu_set` allow CPUs to be add or removed.
3178
3179 :class:`cpu_set` supports the AND, OR, and XOR bitwise operations. For
3180 example, given two cpu_sets, ``one`` and ``two``, ``one | two`` returns a
3181 :class:`cpu_set` containing the cpus enabled both in ``one`` and ``two``.
3182
3183 .. method:: set(i)
3184
3185 Enable CPU *i*.
3186
3187 .. method:: clear(i)
3188
3189 Remove CPU *i*.
3190
3191 .. method:: isset(i)
3192
3193 Return ``True`` if CPU *i* is enabled in the set.
3194
3195 .. method:: count()
3196
3197 Return the number of enabled CPUs in the set.
3198
3199 .. method:: zero()
3200
3201 Clear the set completely.
3202
3203
3204.. function:: sched_setaffinity(pid, mask)
3205
3206 Restrict the process with PID *pid* to a set of CPUs. *mask* is a
3207 :class:`cpu_set` instance.
3208
3209
3210.. function:: sched_getaffinity(pid, size)
3211
3212 Return the :class:`cpu_set` the process with PID *pid* is restricted to. The
3213 result will contain *size* CPUs.
3214
3215
Georg Brandl116aa622007-08-15 14:28:22 +00003216.. _os-path:
3217
3218Miscellaneous System Information
3219--------------------------------
3220
3221
3222.. function:: confstr(name)
3223
3224 Return string-valued system configuration values. *name* specifies the
3225 configuration value to retrieve; it may be a string which is the name of a
3226 defined system value; these names are specified in a number of standards (POSIX,
3227 Unix 95, Unix 98, and others). Some platforms define additional names as well.
3228 The names known to the host operating system are given as the keys of the
3229 ``confstr_names`` dictionary. For configuration variables not included in that
Benjamin Petersonf650e462010-05-06 23:03:05 +00003230 mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00003231
3232 If the configuration value specified by *name* isn't defined, ``None`` is
3233 returned.
3234
3235 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
3236 specific value for *name* is not supported by the host system, even if it is
3237 included in ``confstr_names``, an :exc:`OSError` is raised with
3238 :const:`errno.EINVAL` for the error number.
3239
Benjamin Petersonf650e462010-05-06 23:03:05 +00003240 Availability: Unix
3241
Georg Brandl116aa622007-08-15 14:28:22 +00003242
3243.. data:: confstr_names
3244
3245 Dictionary mapping names accepted by :func:`confstr` to the integer values
3246 defined for those names by the host operating system. This can be used to
Benjamin Petersonf650e462010-05-06 23:03:05 +00003247 determine the set of names known to the system.
3248
3249 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003250
3251
3252.. function:: getloadavg()
3253
Christian Heimesa62da1d2008-01-12 19:39:10 +00003254 Return the number of processes in the system run queue averaged over the last
3255 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Benjamin Petersonf650e462010-05-06 23:03:05 +00003256 unobtainable.
3257
3258 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003259
Georg Brandl116aa622007-08-15 14:28:22 +00003260
3261.. function:: sysconf(name)
3262
3263 Return integer-valued system configuration values. If the configuration value
3264 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
3265 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
3266 provides information on the known names is given by ``sysconf_names``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00003267
Georg Brandlc575c902008-09-13 17:46:05 +00003268 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003269
3270
3271.. data:: sysconf_names
3272
3273 Dictionary mapping names accepted by :func:`sysconf` to the integer values
3274 defined for those names by the host operating system. This can be used to
Benjamin Petersonf650e462010-05-06 23:03:05 +00003275 determine the set of names known to the system.
3276
3277 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00003278
Christian Heimesfaf2f632008-01-06 16:59:19 +00003279The following data values are used to support path manipulation operations. These
Georg Brandl116aa622007-08-15 14:28:22 +00003280are defined for all platforms.
3281
3282Higher-level operations on pathnames are defined in the :mod:`os.path` module.
3283
3284
3285.. data:: curdir
3286
3287 The constant string used by the operating system to refer to the current
Georg Brandlc575c902008-09-13 17:46:05 +00003288 directory. This is ``'.'`` for Windows and POSIX. Also available via
3289 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00003290
3291
3292.. data:: pardir
3293
3294 The constant string used by the operating system to refer to the parent
Georg Brandlc575c902008-09-13 17:46:05 +00003295 directory. This is ``'..'`` for Windows and POSIX. Also available via
3296 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00003297
3298
3299.. data:: sep
3300
Georg Brandlc575c902008-09-13 17:46:05 +00003301 The character used by the operating system to separate pathname components.
3302 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
3303 is not sufficient to be able to parse or concatenate pathnames --- use
Georg Brandl116aa622007-08-15 14:28:22 +00003304 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
3305 useful. Also available via :mod:`os.path`.
3306
3307
3308.. data:: altsep
3309
3310 An alternative character used by the operating system to separate pathname
3311 components, or ``None`` if only one separator character exists. This is set to
3312 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
3313 :mod:`os.path`.
3314
3315
3316.. data:: extsep
3317
3318 The character which separates the base filename from the extension; for example,
3319 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
3320
Georg Brandl116aa622007-08-15 14:28:22 +00003321
3322.. data:: pathsep
3323
3324 The character conventionally used by the operating system to separate search
3325 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
3326 Windows. Also available via :mod:`os.path`.
3327
3328
3329.. data:: defpath
3330
3331 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
3332 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
3333
3334
3335.. data:: linesep
3336
3337 The string used to separate (or, rather, terminate) lines on the current
Georg Brandlc575c902008-09-13 17:46:05 +00003338 platform. This may be a single character, such as ``'\n'`` for POSIX, or
3339 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
3340 *os.linesep* as a line terminator when writing files opened in text mode (the
3341 default); use a single ``'\n'`` instead, on all platforms.
Georg Brandl116aa622007-08-15 14:28:22 +00003342
3343
3344.. data:: devnull
3345
Georg Brandl850a9902010-05-21 22:04:32 +00003346 The file path of the null device. For example: ``'/dev/null'`` for
3347 POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00003348
Georg Brandl116aa622007-08-15 14:28:22 +00003349
3350.. _os-miscfunc:
3351
3352Miscellaneous Functions
3353-----------------------
3354
3355
3356.. function:: urandom(n)
3357
3358 Return a string of *n* random bytes suitable for cryptographic use.
3359
3360 This function returns random bytes from an OS-specific randomness source. The
3361 returned data should be unpredictable enough for cryptographic applications,
3362 though its exact quality depends on the OS implementation. On a UNIX-like
3363 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
3364 If a randomness source is not found, :exc:`NotImplementedError` will be raised.