blob: 1d4b1e164074b230c1c9a8b6d85240f98718d2c6 [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
32.. note::
33
Georg Brandlc575c902008-09-13 17:46:05 +000034 If not separately noted, all functions that claim "Availability: Unix" are
35 supported on Mac OS X, which builds on a Unix core.
36
Benjamin Peterson1baf4652009-12-31 03:11:23 +000037* An "Availability: Unix" note means that this function is commonly found on
38 Unix systems. It does not make any claims about its existence on a specific
39 operating system.
40
41* If not separately noted, all functions that claim "Availability: Unix" are
42 supported on Mac OS X, which builds on a Unix core.
43
Benjamin Petersonf650e462010-05-06 23:03:05 +000044.. Availability notes get their own line and occur at the end of the function
45.. documentation.
46
Georg Brandlc575c902008-09-13 17:46:05 +000047.. note::
48
Christian Heimesa62da1d2008-01-12 19:39:10 +000049 All functions in this module raise :exc:`OSError` in the case of invalid or
50 inaccessible file names and paths, or other arguments that have the correct
51 type, but are not accepted by the operating system.
Georg Brandl116aa622007-08-15 14:28:22 +000052
Georg Brandl116aa622007-08-15 14:28:22 +000053.. exception:: error
54
Christian Heimesa62da1d2008-01-12 19:39:10 +000055 An alias for the built-in :exc:`OSError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +000056
57
58.. data:: name
59
Benjamin Peterson1baf4652009-12-31 03:11:23 +000060 The name of the operating system dependent module imported. The following
61 names have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``,
62 ``'os2'``, ``'ce'``, ``'java'``.
Georg Brandl116aa622007-08-15 14:28:22 +000063
64
Martin v. Löwis011e8422009-05-05 04:43:17 +000065.. _os-filenames:
66
67File Names, Command Line Arguments, and Environment Variables
68-------------------------------------------------------------
69
70In Python, file names, command line arguments, and environment
71variables are represented using the string type. On some systems,
72decoding these strings to and from bytes is necessary before passing
73them to the operating system. Python uses the file system encoding to
74perform this conversion (see :func:`sys.getfilesystemencoding`).
75
76.. versionchanged:: 3.1
77 On some systems, conversion using the file system encoding may
Martin v. Löwis43c57782009-05-10 08:15:24 +000078 fail. In this case, Python uses the ``surrogateescape`` encoding
79 error handler, which means that undecodable bytes are replaced by a
Martin v. Löwis011e8422009-05-05 04:43:17 +000080 Unicode character U+DCxx on decoding, and these are again
81 translated to the original byte on encoding.
82
83
84The file system encoding must guarantee to successfully decode all
85bytes below 128. If the file system encoding fails to provide this
86guarantee, API functions may raise UnicodeErrors.
87
88
Georg Brandl116aa622007-08-15 14:28:22 +000089.. _os-procinfo:
90
91Process Parameters
92------------------
93
94These functions and data items provide information and operate on the current
95process and user.
96
97
98.. data:: environ
99
100 A mapping object representing the string environment. For example,
101 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
102 and is equivalent to ``getenv("HOME")`` in C.
103
104 This mapping is captured the first time the :mod:`os` module is imported,
105 typically during Python startup as part of processing :file:`site.py`. Changes
106 to the environment made after this time are not reflected in ``os.environ``,
107 except for changes made by modifying ``os.environ`` directly.
108
109 If the platform supports the :func:`putenv` function, this mapping may be used
110 to modify the environment as well as query the environment. :func:`putenv` will
111 be called automatically when the mapping is modified.
112
Victor Stinner84ae1182010-05-06 22:05:07 +0000113 On Unix, keys and values use :func:`sys.getfilesystemencoding` and
114 ``'surrogateescape'`` error handler. Use :data:`environb` if you would like
115 to use a different encoding.
116
Georg Brandl116aa622007-08-15 14:28:22 +0000117 .. note::
118
119 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
120 to modify ``os.environ``.
121
122 .. note::
123
Georg Brandlc575c902008-09-13 17:46:05 +0000124 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
125 cause memory leaks. Refer to the system documentation for
126 :cfunc:`putenv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128 If :func:`putenv` is not provided, a modified copy of this mapping may be
129 passed to the appropriate process-creation functions to cause child processes
130 to use a modified environment.
131
Georg Brandl9afde1c2007-11-01 20:32:30 +0000132 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl116aa622007-08-15 14:28:22 +0000133 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl9afde1c2007-11-01 20:32:30 +0000134 automatically when an item is deleted from ``os.environ``, and when
135 one of the :meth:`pop` or :meth:`clear` methods is called.
136
Georg Brandl116aa622007-08-15 14:28:22 +0000137
Victor Stinner84ae1182010-05-06 22:05:07 +0000138.. data:: environb
139
140 Bytes version of :data:`environ`: a mapping object representing the
141 environment as byte strings. :data:`environ` and :data:`environb` are
142 synchronized (modify :data:`environb` updates :data:`environ`, and vice
143 versa).
144
145 Availability: Unix.
146
Benjamin Peterson662c74f2010-05-06 22:09:03 +0000147 .. versionadded:: 3.2
148
Victor Stinner84ae1182010-05-06 22:05:07 +0000149
Georg Brandl116aa622007-08-15 14:28:22 +0000150.. function:: chdir(path)
151 fchdir(fd)
152 getcwd()
153 :noindex:
154
155 These functions are described in :ref:`os-file-dir`.
156
157
Victor Stinner449c4662010-05-08 11:10:09 +0000158.. function:: fsencode(value)
159
160 Encode *value* to bytes for use in the file system, environment variables or
161 the command line. Uses :func:`sys.getfilesystemencoding` and
162 ``'surrogateescape'`` error handler for strings and returns bytes unchanged.
163
164 Availability: Unix.
165
166 .. versionadded:: 3.2
167
168
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000169.. function:: get_exec_path(env=None)
170
171 Returns the list of directories that will be searched for a named
172 executable, similar to a shell, when launching a process.
173 *env*, when specified, should be an environment variable dictionary
174 to lookup the PATH in.
175 By default, when *env* is None, :data:`environ` is used.
176
177 .. versionadded:: 3.2
178
179
Georg Brandl116aa622007-08-15 14:28:22 +0000180.. function:: ctermid()
181
182 Return the filename corresponding to the controlling terminal of the process.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000183
Georg Brandl116aa622007-08-15 14:28:22 +0000184 Availability: Unix.
185
186
187.. function:: getegid()
188
189 Return the effective group id of the current process. This corresponds to the
Benjamin Petersonf650e462010-05-06 23:03:05 +0000190 "set id" bit on the file being executed in the current process.
191
192 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
194
195.. function:: geteuid()
196
197 .. index:: single: user; effective id
198
Benjamin Petersonf650e462010-05-06 23:03:05 +0000199 Return the current process's effective user id.
200
201 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203
204.. function:: getgid()
205
206 .. index:: single: process; group
207
Benjamin Petersonf650e462010-05-06 23:03:05 +0000208 Return the real group id of the current process.
209
210 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000211
212
213.. function:: getgroups()
214
215 Return list of supplemental group ids associated with the current process.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000216
Georg Brandl116aa622007-08-15 14:28:22 +0000217 Availability: Unix.
218
219
Antoine Pitroub7572f02009-12-02 20:46:48 +0000220.. function:: initgroups(username, gid)
221
222 Call the system initgroups() to initialize the group access list with all of
223 the groups of which the specified username is a member, plus the specified
Benjamin Petersonf650e462010-05-06 23:03:05 +0000224 group id.
225
226 Availability: Unix.
Antoine Pitroub7572f02009-12-02 20:46:48 +0000227
228 .. versionadded:: 3.2
229
230
Georg Brandl116aa622007-08-15 14:28:22 +0000231.. function:: getlogin()
232
233 Return the name of the user logged in on the controlling terminal of the
234 process. For most purposes, it is more useful to use the environment variable
235 :envvar:`LOGNAME` to find out who the user is, or
236 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
Benjamin Petersonf650e462010-05-06 23:03:05 +0000237 effective user id.
238
239 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000240
241
242.. function:: getpgid(pid)
243
244 Return the process group id of the process with process id *pid*. If *pid* is 0,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000245 the process group id of the current process is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Benjamin Petersonf650e462010-05-06 23:03:05 +0000247 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249.. function:: getpgrp()
250
251 .. index:: single: process; group
252
Benjamin Petersonf650e462010-05-06 23:03:05 +0000253 Return the id of the current process group.
254
255 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257
258.. function:: getpid()
259
260 .. index:: single: process; id
261
Benjamin Petersonf650e462010-05-06 23:03:05 +0000262 Return the current process id.
263
264 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266
267.. function:: getppid()
268
269 .. index:: single: process; id of parent
270
Benjamin Petersonf650e462010-05-06 23:03:05 +0000271 Return the parent's process id.
272
273 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Georg Brandl1b83a452009-11-28 11:12:26 +0000275
Gregory P. Smithcf02c6a2009-11-27 17:54:17 +0000276.. function:: getresuid()
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000277
278 Return a tuple (ruid, euid, suid) denoting the current process's
Benjamin Petersonf650e462010-05-06 23:03:05 +0000279 real, effective, and saved user ids.
280
281 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000282
Georg Brandl1b83a452009-11-28 11:12:26 +0000283 .. versionadded:: 3.2
284
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000285
Gregory P. Smithcf02c6a2009-11-27 17:54:17 +0000286.. function:: getresgid()
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000287
288 Return a tuple (rgid, egid, sgid) denoting the current process's
Benjamin Petersonf650e462010-05-06 23:03:05 +0000289 real, effective, and saved user ids.
290
291 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000292
Georg Brandl1b83a452009-11-28 11:12:26 +0000293 .. versionadded:: 3.2
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296.. function:: getuid()
297
298 .. index:: single: user; id
299
Benjamin Petersonf650e462010-05-06 23:03:05 +0000300 Return the current process's user id.
301
302 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000303
304
Georg Brandl18244152009-09-02 20:34:52 +0000305.. function:: getenv(key, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000306
Georg Brandl18244152009-09-02 20:34:52 +0000307 Return the value of the environment variable *key* if it exists, or
Victor Stinner84ae1182010-05-06 22:05:07 +0000308 *default* if it doesn't. *key*, *default* and the result are str.
Victor Stinner84ae1182010-05-06 22:05:07 +0000309
310 On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding`
311 and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you
312 would like to use a different encoding.
313
Benjamin Petersonf650e462010-05-06 23:03:05 +0000314 Availability: most flavors of Unix, Windows.
315
Victor Stinner84ae1182010-05-06 22:05:07 +0000316
317.. function:: getenvb(key, default=None)
318
319 Return the value of the environment variable *key* if it exists, or
320 *default* if it doesn't. *key*, *default* and the result are bytes.
Benjamin Peterson0d6fe512010-05-06 22:13:11 +0000321
Victor Stinner84ae1182010-05-06 22:05:07 +0000322 Availability: most flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000323
Benjamin Peterson0d6fe512010-05-06 22:13:11 +0000324 .. versionadded:: 3.2
325
Georg Brandl116aa622007-08-15 14:28:22 +0000326
Georg Brandl18244152009-09-02 20:34:52 +0000327.. function:: putenv(key, value)
Georg Brandl116aa622007-08-15 14:28:22 +0000328
329 .. index:: single: environment variables; setting
330
Georg Brandl18244152009-09-02 20:34:52 +0000331 Set the environment variable named *key* to the string *value*. Such
Georg Brandl116aa622007-08-15 14:28:22 +0000332 changes to the environment affect subprocesses started with :func:`os.system`,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000333 :func:`popen` or :func:`fork` and :func:`execv`.
334
335 Availability: most flavors of Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337 .. note::
338
Georg Brandlc575c902008-09-13 17:46:05 +0000339 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
340 cause memory leaks. Refer to the system documentation for putenv.
Georg Brandl116aa622007-08-15 14:28:22 +0000341
342 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
343 automatically translated into corresponding calls to :func:`putenv`; however,
344 calls to :func:`putenv` don't update ``os.environ``, so it is actually
345 preferable to assign to items of ``os.environ``.
346
347
348.. function:: setegid(egid)
349
Benjamin Petersonf650e462010-05-06 23:03:05 +0000350 Set the current process's effective group id.
351
352 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354
355.. function:: seteuid(euid)
356
Benjamin Petersonf650e462010-05-06 23:03:05 +0000357 Set the current process's effective user id.
358
359 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361
362.. function:: setgid(gid)
363
Benjamin Petersonf650e462010-05-06 23:03:05 +0000364 Set the current process' group id.
365
366 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368
369.. function:: setgroups(groups)
370
371 Set the list of supplemental group ids associated with the current process to
372 *groups*. *groups* must be a sequence, and each element must be an integer
Christian Heimesfaf2f632008-01-06 16:59:19 +0000373 identifying a group. This operation is typically available only to the superuser.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000374
Georg Brandl116aa622007-08-15 14:28:22 +0000375 Availability: Unix.
376
Georg Brandl116aa622007-08-15 14:28:22 +0000377
378.. function:: setpgrp()
379
Christian Heimesfaf2f632008-01-06 16:59:19 +0000380 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
Georg Brandl116aa622007-08-15 14:28:22 +0000381 which version is implemented (if any). See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000382
Georg Brandl116aa622007-08-15 14:28:22 +0000383 Availability: Unix.
384
385
386.. function:: setpgid(pid, pgrp)
387
Christian Heimesfaf2f632008-01-06 16:59:19 +0000388 Call the system call :cfunc:`setpgid` to set the process group id of the
Georg Brandl116aa622007-08-15 14:28:22 +0000389 process with id *pid* to the process group with id *pgrp*. See the Unix manual
Benjamin Petersonf650e462010-05-06 23:03:05 +0000390 for the semantics.
391
392 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394
Georg Brandl116aa622007-08-15 14:28:22 +0000395.. function:: setregid(rgid, egid)
396
Benjamin Petersonf650e462010-05-06 23:03:05 +0000397 Set the current process's real and effective group ids.
398
399 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000400
Georg Brandl1b83a452009-11-28 11:12:26 +0000401
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000402.. function:: setresgid(rgid, egid, sgid)
403
404 Set the current process's real, effective, and saved group ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000405
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000406 Availability: Unix.
407
Georg Brandl1b83a452009-11-28 11:12:26 +0000408 .. versionadded:: 3.2
409
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000410
411.. function:: setresuid(ruid, euid, suid)
412
413 Set the current process's real, effective, and saved user ids.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000414
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000415 Availibility: Unix.
416
Georg Brandl1b83a452009-11-28 11:12:26 +0000417 .. versionadded:: 3.2
418
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000419
420.. function:: setreuid(ruid, euid)
421
Benjamin Petersonf650e462010-05-06 23:03:05 +0000422 Set the current process's real and effective user ids.
423
424 Availability: Unix.
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000425
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427.. function:: getsid(pid)
428
Christian Heimesfaf2f632008-01-06 16:59:19 +0000429 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000430
Georg Brandl116aa622007-08-15 14:28:22 +0000431 Availability: Unix.
432
Georg Brandl116aa622007-08-15 14:28:22 +0000433
434.. function:: setsid()
435
Christian Heimesfaf2f632008-01-06 16:59:19 +0000436 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000437
Georg Brandl116aa622007-08-15 14:28:22 +0000438 Availability: Unix.
439
440
441.. function:: setuid(uid)
442
443 .. index:: single: user; id, setting
444
Benjamin Petersonf650e462010-05-06 23:03:05 +0000445 Set the current process's user id.
446
447 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000450.. placed in this section since it relates to errno.... a little weak
Georg Brandl116aa622007-08-15 14:28:22 +0000451.. function:: strerror(code)
452
453 Return the error message corresponding to the error code in *code*.
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000454 On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
Benjamin Petersonf650e462010-05-06 23:03:05 +0000455 error number, :exc:`ValueError` is raised.
456
457 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000458
459
460.. function:: umask(mask)
461
Benjamin Petersonf650e462010-05-06 23:03:05 +0000462 Set the current numeric umask and return the previous umask.
463
464 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
466
467.. function:: uname()
468
469 .. index::
470 single: gethostname() (in module socket)
471 single: gethostbyaddr() (in module socket)
472
473 Return a 5-tuple containing information identifying the current operating
474 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
475 machine)``. Some systems truncate the nodename to 8 characters or to the
476 leading component; a better way to get the hostname is
477 :func:`socket.gethostname` or even
Benjamin Petersonf650e462010-05-06 23:03:05 +0000478 ``socket.gethostbyaddr(socket.gethostname())``.
479
480 Availability: recent flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482
Georg Brandl18244152009-09-02 20:34:52 +0000483.. function:: unsetenv(key)
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485 .. index:: single: environment variables; deleting
486
Georg Brandl18244152009-09-02 20:34:52 +0000487 Unset (delete) the environment variable named *key*. Such changes to the
Georg Brandl116aa622007-08-15 14:28:22 +0000488 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
Benjamin Petersonf650e462010-05-06 23:03:05 +0000489 :func:`fork` and :func:`execv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000490
491 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
492 automatically translated into a corresponding call to :func:`unsetenv`; however,
493 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
494 preferable to delete items of ``os.environ``.
495
Benjamin Petersonf650e462010-05-06 23:03:05 +0000496 Availability: most flavors of Unix, Windows.
497
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499.. _os-newstreams:
500
501File Object Creation
502--------------------
503
504These functions create new file objects. (See also :func:`open`.)
505
506
507.. function:: fdopen(fd[, mode[, bufsize]])
508
509 .. index:: single: I/O control; buffering
510
511 Return an open file object connected to the file descriptor *fd*. The *mode*
512 and *bufsize* arguments have the same meaning as the corresponding arguments to
Benjamin Petersonf650e462010-05-06 23:03:05 +0000513 the built-in :func:`open` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000514
Georg Brandl55ac8f02007-09-01 13:51:09 +0000515 When specified, the *mode* argument must start with one of the letters
516 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Georg Brandl55ac8f02007-09-01 13:51:09 +0000518 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
519 set on the file descriptor (which the :cfunc:`fdopen` implementation already
520 does on most platforms).
Georg Brandl116aa622007-08-15 14:28:22 +0000521
Benjamin Petersonf650e462010-05-06 23:03:05 +0000522 Availability: Unix, Windows.
523
Georg Brandl116aa622007-08-15 14:28:22 +0000524
Georg Brandl116aa622007-08-15 14:28:22 +0000525.. _os-fd-ops:
526
527File Descriptor Operations
528--------------------------
529
530These functions operate on I/O streams referenced using file descriptors.
531
532File descriptors are small integers corresponding to a file that has been opened
533by the current process. For example, standard input is usually file descriptor
5340, standard output is 1, and standard error is 2. Further files opened by a
535process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
536is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
537by file descriptors.
538
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000539The :meth:`~file.fileno` method can be used to obtain the file descriptor
540associated with a file object when required. Note that using the file
541descriptor directly will bypass the file object methods, ignoring aspects such
542as internal buffering of data.
Georg Brandl116aa622007-08-15 14:28:22 +0000543
544.. function:: close(fd)
545
Benjamin Petersonf650e462010-05-06 23:03:05 +0000546 Close file descriptor *fd*.
547
548 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000549
550 .. note::
551
552 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000553 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
Georg Brandl116aa622007-08-15 14:28:22 +0000554 object" returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000555 :func:`fdopen`, use its :meth:`~file.close` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557
Christian Heimesfdab48e2008-01-20 09:06:41 +0000558.. function:: closerange(fd_low, fd_high)
559
560 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
Benjamin Petersonf650e462010-05-06 23:03:05 +0000561 ignoring errors. Equivalent to::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000562
Georg Brandlc9a5a0e2009-09-01 07:34:27 +0000563 for fd in range(fd_low, fd_high):
Christian Heimesfdab48e2008-01-20 09:06:41 +0000564 try:
565 os.close(fd)
566 except OSError:
567 pass
568
Benjamin Petersonf650e462010-05-06 23:03:05 +0000569 Availability: Unix, Windows.
570
Christian Heimesfdab48e2008-01-20 09:06:41 +0000571
Georg Brandl81f11302007-12-21 08:45:42 +0000572.. function:: device_encoding(fd)
573
574 Return a string describing the encoding of the device associated with *fd*
575 if it is connected to a terminal; else return :const:`None`.
576
577
Georg Brandl116aa622007-08-15 14:28:22 +0000578.. function:: dup(fd)
579
Benjamin Petersonf650e462010-05-06 23:03:05 +0000580 Return a duplicate of file descriptor *fd*.
581
582 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000583
584
585.. function:: dup2(fd, fd2)
586
587 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000588
Georg Brandlc575c902008-09-13 17:46:05 +0000589 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000590
591
Christian Heimes4e30a842007-11-30 22:12:06 +0000592.. function:: fchmod(fd, mode)
593
594 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
Benjamin Petersonf650e462010-05-06 23:03:05 +0000595 for :func:`chmod` for possible values of *mode*.
596
597 Availability: Unix.
Christian Heimes4e30a842007-11-30 22:12:06 +0000598
599
600.. function:: fchown(fd, uid, gid)
601
602 Change the owner and group id of the file given by *fd* to the numeric *uid*
603 and *gid*. To leave one of the ids unchanged, set it to -1.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000604
Christian Heimes4e30a842007-11-30 22:12:06 +0000605 Availability: Unix.
606
607
Georg Brandl116aa622007-08-15 14:28:22 +0000608.. function:: fdatasync(fd)
609
610 Force write of file with filedescriptor *fd* to disk. Does not force update of
Benjamin Petersonf650e462010-05-06 23:03:05 +0000611 metadata.
612
613 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000614
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000615 .. note::
616 This function is not available on MacOS.
617
Georg Brandl116aa622007-08-15 14:28:22 +0000618
619.. function:: fpathconf(fd, name)
620
621 Return system configuration information relevant to an open file. *name*
622 specifies the configuration value to retrieve; it may be a string which is the
623 name of a defined system value; these names are specified in a number of
624 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
625 additional names as well. The names known to the host operating system are
626 given in the ``pathconf_names`` dictionary. For configuration variables not
627 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +0000628
629 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
630 specific value for *name* is not supported by the host system, even if it is
631 included in ``pathconf_names``, an :exc:`OSError` is raised with
632 :const:`errno.EINVAL` for the error number.
633
Benjamin Petersonf650e462010-05-06 23:03:05 +0000634 Availability: Unix.
635
Georg Brandl116aa622007-08-15 14:28:22 +0000636
637.. function:: fstat(fd)
638
Benjamin Petersonf650e462010-05-06 23:03:05 +0000639 Return status for file descriptor *fd*, like :func:`stat`.
640
641 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000642
643
644.. function:: fstatvfs(fd)
645
646 Return information about the filesystem containing the file associated with file
Benjamin Petersonf650e462010-05-06 23:03:05 +0000647 descriptor *fd*, like :func:`statvfs`.
648
649 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000650
651
652.. function:: fsync(fd)
653
654 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
655 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
656
657 If you're starting with a Python file object *f*, first do ``f.flush()``, and
658 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
Benjamin Petersonf650e462010-05-06 23:03:05 +0000659 with *f* are written to disk.
660
661 Availability: Unix, and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000662
663
664.. function:: ftruncate(fd, length)
665
666 Truncate the file corresponding to file descriptor *fd*, so that it is at most
Benjamin Petersonf650e462010-05-06 23:03:05 +0000667 *length* bytes in size.
668
669 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000670
671
672.. function:: isatty(fd)
673
674 Return ``True`` if the file descriptor *fd* is open and connected to a
Benjamin Petersonf650e462010-05-06 23:03:05 +0000675 tty(-like) device, else ``False``.
676
677 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000678
679
680.. function:: lseek(fd, pos, how)
681
Christian Heimesfaf2f632008-01-06 16:59:19 +0000682 Set the current position of file descriptor *fd* to position *pos*, modified
683 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
684 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
685 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Benjamin Petersonf650e462010-05-06 23:03:05 +0000686 the file.
687
688 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690
691.. function:: open(file, flags[, mode])
692
Georg Brandlf4a41232008-05-26 17:55:52 +0000693 Open the file *file* and set various flags according to *flags* and possibly
694 its mode according to *mode*. The default *mode* is ``0o777`` (octal), and
695 the current umask value is first masked out. Return the file descriptor for
Benjamin Petersonf650e462010-05-06 23:03:05 +0000696 the newly opened file.
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698 For a description of the flag and mode values, see the C run-time documentation;
699 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
700 this module too (see below).
701
Benjamin Petersonf650e462010-05-06 23:03:05 +0000702 Availability: Unix, Windows.
703
Georg Brandl116aa622007-08-15 14:28:22 +0000704 .. note::
705
Georg Brandl502d9a52009-07-26 15:02:41 +0000706 This function is intended for low-level I/O. For normal usage, use the
707 built-in function :func:`open`, which returns a "file object" with
Benjamin Petersonf650e462010-05-06 23:03:05 +0000708 :meth:`~file.read` and :meth:`~file.wprite` methods (and many more). To
Georg Brandl502d9a52009-07-26 15:02:41 +0000709 wrap a file descriptor in a "file object", use :func:`fdopen`.
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711
712.. function:: openpty()
713
714 .. index:: module: pty
715
716 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
717 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Benjamin Petersonf650e462010-05-06 23:03:05 +0000718 approach, use the :mod:`pty` module.
719
720 Availability: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000721
722
723.. function:: pipe()
724
725 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
Benjamin Petersonf650e462010-05-06 23:03:05 +0000726 and writing, respectively.
727
728 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000729
730
731.. function:: read(fd, n)
732
Georg Brandlb90be692009-07-29 16:14:16 +0000733 Read at most *n* bytes from file descriptor *fd*. Return a bytestring containing the
Georg Brandl116aa622007-08-15 14:28:22 +0000734 bytes read. If the end of the file referred to by *fd* has been reached, an
Benjamin Petersonf650e462010-05-06 23:03:05 +0000735 empty bytes object is returned.
736
737 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000738
739 .. note::
740
741 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000742 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a "file object"
Georg Brandl116aa622007-08-15 14:28:22 +0000743 returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000744 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
745 :meth:`~file.readline` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000746
747
748.. function:: tcgetpgrp(fd)
749
750 Return the process group associated with the terminal given by *fd* (an open
Benjamin Petersonf650e462010-05-06 23:03:05 +0000751 file descriptor as returned by :func:`os.open`).
752
753 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000754
755
756.. function:: tcsetpgrp(fd, pg)
757
758 Set the process group associated with the terminal given by *fd* (an open file
Benjamin Petersonf650e462010-05-06 23:03:05 +0000759 descriptor as returned by :func:`os.open`) to *pg*.
760
761 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000762
763
764.. function:: ttyname(fd)
765
766 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +0000767 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Benjamin Petersonf650e462010-05-06 23:03:05 +0000768 exception is raised.
769
770 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000771
772
773.. function:: write(fd, str)
774
Georg Brandlb90be692009-07-29 16:14:16 +0000775 Write the bytestring in *str* to file descriptor *fd*. Return the number of
Benjamin Petersonf650e462010-05-06 23:03:05 +0000776 bytes actually written.
777
778 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000779
780 .. note::
781
782 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000783 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
Georg Brandl116aa622007-08-15 14:28:22 +0000784 object" returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000785 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
786 :meth:`~file.write` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000787
Georg Brandlaf265f42008-12-07 15:06:20 +0000788The following constants are options for the *flags* parameter to the
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000789:func:`~os.open` function. They can be combined using the bitwise OR operator
Georg Brandlaf265f42008-12-07 15:06:20 +0000790``|``. Some of them are not available on all platforms. For descriptions of
791their availability and use, consult the :manpage:`open(2)` manual page on Unix
Doug Hellmanneb097fc2009-09-20 20:56:56 +0000792or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000793
794
795.. data:: O_RDONLY
796 O_WRONLY
797 O_RDWR
798 O_APPEND
799 O_CREAT
800 O_EXCL
801 O_TRUNC
802
Georg Brandlaf265f42008-12-07 15:06:20 +0000803 These constants are available on Unix and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000804
805
806.. data:: O_DSYNC
807 O_RSYNC
808 O_SYNC
809 O_NDELAY
810 O_NONBLOCK
811 O_NOCTTY
812 O_SHLOCK
813 O_EXLOCK
814
Georg Brandlaf265f42008-12-07 15:06:20 +0000815 These constants are only available on Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000816
817
818.. data:: O_BINARY
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000819 O_NOINHERIT
Georg Brandl116aa622007-08-15 14:28:22 +0000820 O_SHORT_LIVED
821 O_TEMPORARY
822 O_RANDOM
823 O_SEQUENTIAL
824 O_TEXT
825
Georg Brandlaf265f42008-12-07 15:06:20 +0000826 These constants are only available on Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000827
828
Alexandre Vassalottibee32532008-05-16 18:15:12 +0000829.. data:: O_ASYNC
830 O_DIRECT
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000831 O_DIRECTORY
832 O_NOFOLLOW
833 O_NOATIME
834
Georg Brandlaf265f42008-12-07 15:06:20 +0000835 These constants are GNU extensions and not present if they are not defined by
836 the C library.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000837
838
Georg Brandl116aa622007-08-15 14:28:22 +0000839.. data:: SEEK_SET
840 SEEK_CUR
841 SEEK_END
842
843 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
Georg Brandlc575c902008-09-13 17:46:05 +0000844 respectively. Availability: Windows, Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000845
Georg Brandl116aa622007-08-15 14:28:22 +0000846
847.. _os-file-dir:
848
849Files and Directories
850---------------------
851
Georg Brandl116aa622007-08-15 14:28:22 +0000852.. function:: access(path, mode)
853
854 Use the real uid/gid to test for access to *path*. Note that most operations
855 will use the effective uid/gid, therefore this routine can be used in a
856 suid/sgid environment to test if the invoking user has the specified access to
857 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
858 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
859 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
860 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
Benjamin Petersonf650e462010-05-06 23:03:05 +0000861 information.
862
863 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000864
865 .. note::
866
Georg Brandl502d9a52009-07-26 15:02:41 +0000867 Using :func:`access` to check if a user is authorized to e.g. open a file
868 before actually doing so using :func:`open` creates a security hole,
869 because the user might exploit the short time interval between checking
870 and opening the file to manipulate it.
Georg Brandl116aa622007-08-15 14:28:22 +0000871
872 .. note::
873
874 I/O operations may fail even when :func:`access` indicates that they would
875 succeed, particularly for operations on network filesystems which may have
876 permissions semantics beyond the usual POSIX permission-bit model.
877
878
879.. data:: F_OK
880
881 Value to pass as the *mode* parameter of :func:`access` to test the existence of
882 *path*.
883
884
885.. data:: R_OK
886
887 Value to include in the *mode* parameter of :func:`access` to test the
888 readability of *path*.
889
890
891.. data:: W_OK
892
893 Value to include in the *mode* parameter of :func:`access` to test the
894 writability of *path*.
895
896
897.. data:: X_OK
898
899 Value to include in the *mode* parameter of :func:`access` to determine if
900 *path* can be executed.
901
902
903.. function:: chdir(path)
904
905 .. index:: single: directory; changing
906
Benjamin Petersonf650e462010-05-06 23:03:05 +0000907 Change the current working directory to *path*.
908
909 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000910
911
912.. function:: fchdir(fd)
913
914 Change the current working directory to the directory represented by the file
915 descriptor *fd*. The descriptor must refer to an opened directory, not an open
Benjamin Petersonf650e462010-05-06 23:03:05 +0000916 file.
917
918 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000919
Georg Brandl116aa622007-08-15 14:28:22 +0000920
921.. function:: getcwd()
922
Martin v. Löwis011e8422009-05-05 04:43:17 +0000923 Return a string representing the current working directory.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000924
Martin v. Löwis011e8422009-05-05 04:43:17 +0000925 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Benjamin Petersonf650e462010-05-06 23:03:05 +0000927
Martin v. Löwisa731b992008-10-07 06:36:31 +0000928.. function:: getcwdb()
Georg Brandl116aa622007-08-15 14:28:22 +0000929
Georg Brandl76e55382008-10-08 16:34:57 +0000930 Return a bytestring representing the current working directory.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000931
Georg Brandlc575c902008-09-13 17:46:05 +0000932 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000933
Georg Brandl116aa622007-08-15 14:28:22 +0000934
935.. function:: chflags(path, flags)
936
937 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
938 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
939
940 * ``UF_NODUMP``
941 * ``UF_IMMUTABLE``
942 * ``UF_APPEND``
943 * ``UF_OPAQUE``
944 * ``UF_NOUNLINK``
945 * ``SF_ARCHIVED``
946 * ``SF_IMMUTABLE``
947 * ``SF_APPEND``
948 * ``SF_NOUNLINK``
949 * ``SF_SNAPSHOT``
950
Georg Brandlc575c902008-09-13 17:46:05 +0000951 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000952
Georg Brandl116aa622007-08-15 14:28:22 +0000953
954.. function:: chroot(path)
955
956 Change the root directory of the current process to *path*. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000957 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000958
Georg Brandl116aa622007-08-15 14:28:22 +0000959
960.. function:: chmod(path, mode)
961
962 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000963 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl116aa622007-08-15 14:28:22 +0000964 combinations of them:
965
Alexandre Vassalottic22c6f22009-07-21 00:51:58 +0000966 * :data:`stat.S_ISUID`
967 * :data:`stat.S_ISGID`
968 * :data:`stat.S_ENFMT`
969 * :data:`stat.S_ISVTX`
970 * :data:`stat.S_IREAD`
971 * :data:`stat.S_IWRITE`
972 * :data:`stat.S_IEXEC`
973 * :data:`stat.S_IRWXU`
974 * :data:`stat.S_IRUSR`
975 * :data:`stat.S_IWUSR`
976 * :data:`stat.S_IXUSR`
977 * :data:`stat.S_IRWXG`
978 * :data:`stat.S_IRGRP`
979 * :data:`stat.S_IWGRP`
980 * :data:`stat.S_IXGRP`
981 * :data:`stat.S_IRWXO`
982 * :data:`stat.S_IROTH`
983 * :data:`stat.S_IWOTH`
984 * :data:`stat.S_IXOTH`
Georg Brandl116aa622007-08-15 14:28:22 +0000985
Georg Brandlc575c902008-09-13 17:46:05 +0000986 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000987
988 .. note::
989
990 Although Windows supports :func:`chmod`, you can only set the file's read-only
991 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
992 constants or a corresponding integer value). All other bits are
993 ignored.
994
995
996.. function:: chown(path, uid, gid)
997
998 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
Benjamin Petersonf650e462010-05-06 23:03:05 +0000999 one of the ids unchanged, set it to -1.
1000
1001 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001002
1003
1004.. function:: lchflags(path, flags)
1005
1006 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
Benjamin Petersonf650e462010-05-06 23:03:05 +00001007 follow symbolic links.
1008
1009 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001010
Georg Brandl116aa622007-08-15 14:28:22 +00001011
Christian Heimes93852662007-12-01 12:22:32 +00001012.. function:: lchmod(path, mode)
1013
1014 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
1015 affects the symlink rather than the target. See the docs for :func:`chmod`
Benjamin Petersonf650e462010-05-06 23:03:05 +00001016 for possible values of *mode*.
1017
1018 Availability: Unix.
Christian Heimes93852662007-12-01 12:22:32 +00001019
Christian Heimes93852662007-12-01 12:22:32 +00001020
Georg Brandl116aa622007-08-15 14:28:22 +00001021.. function:: lchown(path, uid, gid)
1022
Christian Heimesfaf2f632008-01-06 16:59:19 +00001023 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Benjamin Petersonf650e462010-05-06 23:03:05 +00001024 function will not follow symbolic links.
1025
1026 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001027
Georg Brandl116aa622007-08-15 14:28:22 +00001028
Benjamin Peterson5879d412009-03-30 14:51:56 +00001029.. function:: link(source, link_name)
Georg Brandl116aa622007-08-15 14:28:22 +00001030
Benjamin Petersonf650e462010-05-06 23:03:05 +00001031 Create a hard link pointing to *source* named *link_name*.
1032
1033 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001034
1035
1036.. function:: listdir(path)
1037
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001038 Return a list containing the names of the entries in the directory given by
1039 *path*. The list is in arbitrary order. It does not include the special
1040 entries ``'.'`` and ``'..'`` even if they are present in the directory.
Georg Brandl116aa622007-08-15 14:28:22 +00001041
Martin v. Löwis011e8422009-05-05 04:43:17 +00001042 This function can be called with a bytes or string argument, and returns
1043 filenames of the same datatype.
Georg Brandl116aa622007-08-15 14:28:22 +00001044
Benjamin Petersonf650e462010-05-06 23:03:05 +00001045 Availability: Unix, Windows.
1046
Georg Brandl116aa622007-08-15 14:28:22 +00001047
1048.. function:: lstat(path)
1049
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001050 Like :func:`stat`, but do not follow symbolic links. This is an alias for
1051 :func:`stat` on platforms that do not support symbolic links, such as
1052 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001053
1054
1055.. function:: mkfifo(path[, mode])
1056
Georg Brandlf4a41232008-05-26 17:55:52 +00001057 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The
1058 default *mode* is ``0o666`` (octal). The current umask value is first masked
Benjamin Petersonf650e462010-05-06 23:03:05 +00001059 out from the mode.
Georg Brandl116aa622007-08-15 14:28:22 +00001060
1061 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
1062 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
1063 rendezvous between "client" and "server" type processes: the server opens the
1064 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
1065 doesn't open the FIFO --- it just creates the rendezvous point.
1066
Benjamin Petersonf650e462010-05-06 23:03:05 +00001067 Availability: Unix.
1068
Georg Brandl116aa622007-08-15 14:28:22 +00001069
Georg Brandl18244152009-09-02 20:34:52 +00001070.. function:: mknod(filename[, mode=0o600[, device]])
Georg Brandl116aa622007-08-15 14:28:22 +00001071
1072 Create a filesystem node (file, device special file or named pipe) named
Georg Brandl18244152009-09-02 20:34:52 +00001073 *filename*. *mode* specifies both the permissions to use and the type of node
1074 to be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
1075 ``stat.S_IFCHR``, ``stat.S_IFBLK``, and ``stat.S_IFIFO`` (those constants are
1076 available in :mod:`stat`). For ``stat.S_IFCHR`` and ``stat.S_IFBLK``,
1077 *device* defines the newly created device special file (probably using
Georg Brandl116aa622007-08-15 14:28:22 +00001078 :func:`os.makedev`), otherwise it is ignored.
1079
Georg Brandl116aa622007-08-15 14:28:22 +00001080
1081.. function:: major(device)
1082
Christian Heimesfaf2f632008-01-06 16:59:19 +00001083 Extract the device major number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +00001084 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
1085
Georg Brandl116aa622007-08-15 14:28:22 +00001086
1087.. function:: minor(device)
1088
Christian Heimesfaf2f632008-01-06 16:59:19 +00001089 Extract the device minor number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +00001090 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
1091
Georg Brandl116aa622007-08-15 14:28:22 +00001092
1093.. function:: makedev(major, minor)
1094
Christian Heimesfaf2f632008-01-06 16:59:19 +00001095 Compose a raw device number from the major and minor device numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001096
Georg Brandl116aa622007-08-15 14:28:22 +00001097
1098.. function:: mkdir(path[, mode])
1099
Georg Brandlf4a41232008-05-26 17:55:52 +00001100 Create a directory named *path* with numeric mode *mode*. The default *mode*
1101 is ``0o777`` (octal). On some systems, *mode* is ignored. Where it is used,
Benjamin Petersonf650e462010-05-06 23:03:05 +00001102 the current umask value is first masked out.
Georg Brandl116aa622007-08-15 14:28:22 +00001103
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001104 It is also possible to create temporary directories; see the
1105 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1106
Benjamin Petersonf650e462010-05-06 23:03:05 +00001107 Availability: Unix, Windows.
1108
Georg Brandl116aa622007-08-15 14:28:22 +00001109
1110.. function:: makedirs(path[, mode])
1111
1112 .. index::
1113 single: directory; creating
1114 single: UNC paths; and os.makedirs()
1115
1116 Recursive directory creation function. Like :func:`mkdir`, but makes all
Georg Brandlf4a41232008-05-26 17:55:52 +00001117 intermediate-level directories needed to contain the leaf directory. Throws
1118 an :exc:`error` exception if the leaf directory already exists or cannot be
1119 created. The default *mode* is ``0o777`` (octal). On some systems, *mode*
1120 is ignored. Where it is used, the current umask value is first masked out.
Georg Brandl116aa622007-08-15 14:28:22 +00001121
1122 .. note::
1123
1124 :func:`makedirs` will become confused if the path elements to create include
Christian Heimesfaf2f632008-01-06 16:59:19 +00001125 :data:`os.pardir`.
Georg Brandl116aa622007-08-15 14:28:22 +00001126
Georg Brandl55ac8f02007-09-01 13:51:09 +00001127 This function handles UNC paths correctly.
Georg Brandl116aa622007-08-15 14:28:22 +00001128
1129
1130.. function:: pathconf(path, name)
1131
1132 Return system configuration information relevant to a named file. *name*
1133 specifies the configuration value to retrieve; it may be a string which is the
1134 name of a defined system value; these names are specified in a number of
1135 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1136 additional names as well. The names known to the host operating system are
1137 given in the ``pathconf_names`` dictionary. For configuration variables not
1138 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00001139
1140 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1141 specific value for *name* is not supported by the host system, even if it is
1142 included in ``pathconf_names``, an :exc:`OSError` is raised with
1143 :const:`errno.EINVAL` for the error number.
1144
Benjamin Petersonf650e462010-05-06 23:03:05 +00001145 Availability: Unix.
1146
Georg Brandl116aa622007-08-15 14:28:22 +00001147
1148.. data:: pathconf_names
1149
1150 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1151 the integer values defined for those names by the host operating system. This
1152 can be used to determine the set of names known to the system. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001153 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001154
1155
1156.. function:: readlink(path)
1157
1158 Return a string representing the path to which the symbolic link points. The
1159 result may be either an absolute or relative pathname; if it is relative, it may
1160 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1161 result)``.
1162
Georg Brandl76e55382008-10-08 16:34:57 +00001163 If the *path* is a string object, the result will also be a string object,
1164 and the call may raise an UnicodeDecodeError. If the *path* is a bytes
1165 object, the result will be a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +00001166
Georg Brandlc575c902008-09-13 17:46:05 +00001167 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001168
1169
1170.. function:: remove(path)
1171
Georg Brandla6053b42009-09-01 08:11:14 +00001172 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
1173 raised; see :func:`rmdir` below to remove a directory. This is identical to
1174 the :func:`unlink` function documented below. On Windows, attempting to
1175 remove a file that is in use causes an exception to be raised; on Unix, the
1176 directory entry is removed but the storage allocated to the file is not made
Benjamin Petersonf650e462010-05-06 23:03:05 +00001177 available until the original file is no longer in use.
1178
1179 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001180
1181
1182.. function:: removedirs(path)
1183
1184 .. index:: single: directory; deleting
1185
Christian Heimesfaf2f632008-01-06 16:59:19 +00001186 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl116aa622007-08-15 14:28:22 +00001187 leaf directory is successfully removed, :func:`removedirs` tries to
1188 successively remove every parent directory mentioned in *path* until an error
1189 is raised (which is ignored, because it generally means that a parent directory
1190 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1191 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1192 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1193 successfully removed.
1194
Georg Brandl116aa622007-08-15 14:28:22 +00001195
1196.. function:: rename(src, dst)
1197
1198 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1199 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Christian Heimesfaf2f632008-01-06 16:59:19 +00001200 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl116aa622007-08-15 14:28:22 +00001201 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1202 the renaming will be an atomic operation (this is a POSIX requirement). On
1203 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1204 file; there may be no way to implement an atomic rename when *dst* names an
Benjamin Petersonf650e462010-05-06 23:03:05 +00001205 existing file.
1206
1207 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001208
1209
1210.. function:: renames(old, new)
1211
1212 Recursive directory or file renaming function. Works like :func:`rename`, except
1213 creation of any intermediate directories needed to make the new pathname good is
1214 attempted first. After the rename, directories corresponding to rightmost path
1215 segments of the old name will be pruned away using :func:`removedirs`.
1216
Georg Brandl116aa622007-08-15 14:28:22 +00001217 .. note::
1218
1219 This function can fail with the new directory structure made if you lack
1220 permissions needed to remove the leaf directory or file.
1221
1222
1223.. function:: rmdir(path)
1224
Georg Brandla6053b42009-09-01 08:11:14 +00001225 Remove (delete) the directory *path*. Only works when the directory is
1226 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
Benjamin Petersonf650e462010-05-06 23:03:05 +00001227 directory trees, :func:`shutil.rmtree` can be used.
1228
1229 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001230
1231
1232.. function:: stat(path)
1233
1234 Perform a :cfunc:`stat` system call on the given path. The return value is an
1235 object whose attributes correspond to the members of the :ctype:`stat`
1236 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1237 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
Christian Heimesfaf2f632008-01-06 16:59:19 +00001238 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
Georg Brandl116aa622007-08-15 14:28:22 +00001239 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1240 access), :attr:`st_mtime` (time of most recent content modification),
1241 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1242 Unix, or the time of creation on Windows)::
1243
1244 >>> import os
1245 >>> statinfo = os.stat('somefile.txt')
1246 >>> statinfo
Georg Brandlf66df2b2010-01-16 14:41:21 +00001247 (33188, 422511, 769, 1, 1032, 100, 926, 1105022698,1105022732, 1105022732)
Georg Brandl116aa622007-08-15 14:28:22 +00001248 >>> statinfo.st_size
Georg Brandlf66df2b2010-01-16 14:41:21 +00001249 926
Georg Brandl116aa622007-08-15 14:28:22 +00001250 >>>
1251
Georg Brandl116aa622007-08-15 14:28:22 +00001252
1253 On some Unix systems (such as Linux), the following attributes may also be
1254 available: :attr:`st_blocks` (number of blocks allocated for file),
1255 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1256 inode device). :attr:`st_flags` (user defined flags for file).
1257
1258 On other Unix systems (such as FreeBSD), the following attributes may be
1259 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1260 (file generation number), :attr:`st_birthtime` (time of file creation).
1261
1262 On Mac OS systems, the following attributes may also be available:
1263 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1264
Georg Brandl116aa622007-08-15 14:28:22 +00001265 .. index:: module: stat
1266
1267 For backward compatibility, the return value of :func:`stat` is also accessible
1268 as a tuple of at least 10 integers giving the most important (and portable)
1269 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1270 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1271 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1272 :attr:`st_ctime`. More items may be added at the end by some implementations.
1273 The standard module :mod:`stat` defines functions and constants that are useful
1274 for extracting information from a :ctype:`stat` structure. (On Windows, some
1275 items are filled with dummy values.)
1276
1277 .. note::
1278
1279 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1280 :attr:`st_ctime` members depends on the operating system and the file system.
1281 For example, on Windows systems using the FAT or FAT32 file systems,
1282 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1283 resolution. See your operating system documentation for details.
1284
Georg Brandlc575c902008-09-13 17:46:05 +00001285 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001286
Georg Brandl116aa622007-08-15 14:28:22 +00001287
1288.. function:: stat_float_times([newvalue])
1289
1290 Determine whether :class:`stat_result` represents time stamps as float objects.
1291 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1292 ``False``, future calls return ints. If *newvalue* is omitted, return the
1293 current setting.
1294
1295 For compatibility with older Python versions, accessing :class:`stat_result` as
1296 a tuple always returns integers.
1297
Georg Brandl55ac8f02007-09-01 13:51:09 +00001298 Python now returns float values by default. Applications which do not work
1299 correctly with floating point time stamps can use this function to restore the
1300 old behaviour.
Georg Brandl116aa622007-08-15 14:28:22 +00001301
1302 The resolution of the timestamps (that is the smallest possible fraction)
1303 depends on the system. Some systems only support second resolution; on these
1304 systems, the fraction will always be zero.
1305
1306 It is recommended that this setting is only changed at program startup time in
1307 the *__main__* module; libraries should never change this setting. If an
1308 application uses a library that works incorrectly if floating point time stamps
1309 are processed, this application should turn the feature off until the library
1310 has been corrected.
1311
1312
1313.. function:: statvfs(path)
1314
1315 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1316 an object whose attributes describe the filesystem on the given path, and
1317 correspond to the members of the :ctype:`statvfs` structure, namely:
1318 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1319 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
Benjamin Petersonf650e462010-05-06 23:03:05 +00001320 :attr:`f_flag`, :attr:`f_namemax`.
1321
1322 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001323
Georg Brandl116aa622007-08-15 14:28:22 +00001324
Benjamin Peterson5879d412009-03-30 14:51:56 +00001325.. function:: symlink(source, link_name)
Georg Brandl116aa622007-08-15 14:28:22 +00001326
Benjamin Petersonf650e462010-05-06 23:03:05 +00001327 Create a symbolic link pointing to *source* named *link_name*.
1328
1329 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001330
1331
Georg Brandl116aa622007-08-15 14:28:22 +00001332.. function:: unlink(path)
1333
Georg Brandla6053b42009-09-01 08:11:14 +00001334 Remove (delete) the file *path*. This is the same function as
1335 :func:`remove`; the :func:`unlink` name is its traditional Unix
Benjamin Petersonf650e462010-05-06 23:03:05 +00001336 name.
1337
1338 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001339
1340
1341.. function:: utime(path, times)
1342
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00001343 Set the access and modified times of the file specified by *path*. If *times*
1344 is ``None``, then the file's access and modified times are set to the current
1345 time. (The effect is similar to running the Unix program :program:`touch` on
1346 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1347 ``(atime, mtime)`` which is used to set the access and modified times,
1348 respectively. Whether a directory can be given for *path* depends on whether
1349 the operating system implements directories as files (for example, Windows
1350 does not). Note that the exact times you set here may not be returned by a
1351 subsequent :func:`stat` call, depending on the resolution with which your
1352 operating system records access and modification times; see :func:`stat`.
Georg Brandl116aa622007-08-15 14:28:22 +00001353
Georg Brandlc575c902008-09-13 17:46:05 +00001354 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001355
1356
Georg Brandl18244152009-09-02 20:34:52 +00001357.. function:: walk(top, topdown=True, onerror=None, followlinks=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001358
1359 .. index::
1360 single: directory; walking
1361 single: directory; traversal
1362
Christian Heimesfaf2f632008-01-06 16:59:19 +00001363 Generate the file names in a directory tree by walking the tree
1364 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl116aa622007-08-15 14:28:22 +00001365 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1366 filenames)``.
1367
1368 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1369 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1370 *filenames* is a list of the names of the non-directory files in *dirpath*.
1371 Note that the names in the lists contain no path components. To get a full path
1372 (which begins with *top*) to a file or directory in *dirpath*, do
1373 ``os.path.join(dirpath, name)``.
1374
Christian Heimesfaf2f632008-01-06 16:59:19 +00001375 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001376 directory is generated before the triples for any of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001377 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001378 directory is generated after the triples for all of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001379 (directories are generated bottom-up).
Georg Brandl116aa622007-08-15 14:28:22 +00001380
Christian Heimesfaf2f632008-01-06 16:59:19 +00001381 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl116aa622007-08-15 14:28:22 +00001382 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1383 recurse into the subdirectories whose names remain in *dirnames*; this can be
1384 used to prune the search, impose a specific order of visiting, or even to inform
1385 :func:`walk` about directories the caller creates or renames before it resumes
Christian Heimesfaf2f632008-01-06 16:59:19 +00001386 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl116aa622007-08-15 14:28:22 +00001387 ineffective, because in bottom-up mode the directories in *dirnames* are
1388 generated before *dirpath* itself is generated.
1389
Christian Heimesfaf2f632008-01-06 16:59:19 +00001390 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl116aa622007-08-15 14:28:22 +00001391 argument *onerror* is specified, it should be a function; it will be called with
1392 one argument, an :exc:`OSError` instance. It can report the error to continue
1393 with the walk, or raise the exception to abort the walk. Note that the filename
1394 is available as the ``filename`` attribute of the exception object.
1395
1396 By default, :func:`walk` will not walk down into symbolic links that resolve to
Christian Heimesfaf2f632008-01-06 16:59:19 +00001397 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl116aa622007-08-15 14:28:22 +00001398 symlinks, on systems that support them.
1399
Georg Brandl116aa622007-08-15 14:28:22 +00001400 .. note::
1401
Christian Heimesfaf2f632008-01-06 16:59:19 +00001402 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl116aa622007-08-15 14:28:22 +00001403 link points to a parent directory of itself. :func:`walk` does not keep track of
1404 the directories it visited already.
1405
1406 .. note::
1407
1408 If you pass a relative pathname, don't change the current working directory
1409 between resumptions of :func:`walk`. :func:`walk` never changes the current
1410 directory, and assumes that its caller doesn't either.
1411
1412 This example displays the number of bytes taken by non-directory files in each
1413 directory under the starting directory, except that it doesn't look under any
1414 CVS subdirectory::
1415
1416 import os
1417 from os.path import join, getsize
1418 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001419 print(root, "consumes", end=" ")
1420 print(sum(getsize(join(root, name)) for name in files), end=" ")
1421 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00001422 if 'CVS' in dirs:
1423 dirs.remove('CVS') # don't visit CVS directories
1424
Christian Heimesfaf2f632008-01-06 16:59:19 +00001425 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl116aa622007-08-15 14:28:22 +00001426 doesn't allow deleting a directory before the directory is empty::
1427
Christian Heimesfaf2f632008-01-06 16:59:19 +00001428 # Delete everything reachable from the directory named in "top",
Georg Brandl116aa622007-08-15 14:28:22 +00001429 # assuming there are no symbolic links.
1430 # CAUTION: This is dangerous! For example, if top == '/', it
1431 # could delete all your disk files.
1432 import os
1433 for root, dirs, files in os.walk(top, topdown=False):
1434 for name in files:
1435 os.remove(os.path.join(root, name))
1436 for name in dirs:
1437 os.rmdir(os.path.join(root, name))
1438
Georg Brandl116aa622007-08-15 14:28:22 +00001439
1440.. _os-process:
1441
1442Process Management
1443------------------
1444
1445These functions may be used to create and manage processes.
1446
1447The various :func:`exec\*` functions take a list of arguments for the new
1448program loaded into the process. In each case, the first of these arguments is
1449passed to the new program as its own name rather than as an argument a user may
1450have typed on a command line. For the C programmer, this is the ``argv[0]``
1451passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1452['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1453to be ignored.
1454
1455
1456.. function:: abort()
1457
1458 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1459 behavior is to produce a core dump; on Windows, the process immediately returns
1460 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1461 to register a handler for :const:`SIGABRT` will behave differently.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001462
Georg Brandlc575c902008-09-13 17:46:05 +00001463 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001464
1465
1466.. function:: execl(path, arg0, arg1, ...)
1467 execle(path, arg0, arg1, ..., env)
1468 execlp(file, arg0, arg1, ...)
1469 execlpe(file, arg0, arg1, ..., env)
1470 execv(path, args)
1471 execve(path, args, env)
1472 execvp(file, args)
1473 execvpe(file, args, env)
1474
1475 These functions all execute a new program, replacing the current process; they
1476 do not return. On Unix, the new executable is loaded into the current process,
Christian Heimesfaf2f632008-01-06 16:59:19 +00001477 and will have the same process id as the caller. Errors will be reported as
Georg Brandl48310cd2009-01-03 21:18:54 +00001478 :exc:`OSError` exceptions.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001479
1480 The current process is replaced immediately. Open file objects and
1481 descriptors are not flushed, so if there may be data buffered
1482 on these open files, you should flush them using
1483 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
1484 :func:`exec\*` function.
Georg Brandl116aa622007-08-15 14:28:22 +00001485
Christian Heimesfaf2f632008-01-06 16:59:19 +00001486 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1487 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001488 to work with if the number of parameters is fixed when the code is written; the
1489 individual parameters simply become additional parameters to the :func:`execl\*`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001490 functions. The "v" variants are good when the number of parameters is
Georg Brandl116aa622007-08-15 14:28:22 +00001491 variable, with the arguments being passed in a list or tuple as the *args*
1492 parameter. In either case, the arguments to the child process should start with
1493 the name of the command being run, but this is not enforced.
1494
Christian Heimesfaf2f632008-01-06 16:59:19 +00001495 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001496 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1497 :envvar:`PATH` environment variable to locate the program *file*. When the
1498 environment is being replaced (using one of the :func:`exec\*e` variants,
1499 discussed in the next paragraph), the new environment is used as the source of
1500 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1501 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1502 locate the executable; *path* must contain an appropriate absolute or relative
1503 path.
1504
1505 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Christian Heimesfaf2f632008-01-06 16:59:19 +00001506 that these all end in "e"), the *env* parameter must be a mapping which is
Christian Heimesa342c012008-04-20 21:01:16 +00001507 used to define the environment variables for the new process (these are used
1508 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl116aa622007-08-15 14:28:22 +00001509 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
Georg Brandl48310cd2009-01-03 21:18:54 +00001510 inherit the environment of the current process.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001511
1512 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001513
1514
1515.. function:: _exit(n)
1516
1517 Exit to the system with status *n*, without calling cleanup handlers, flushing
Benjamin Petersonf650e462010-05-06 23:03:05 +00001518 stdio buffers, etc.
1519
1520 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001521
1522 .. note::
1523
1524 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1525 be used in the child process after a :func:`fork`.
1526
Christian Heimesfaf2f632008-01-06 16:59:19 +00001527The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl116aa622007-08-15 14:28:22 +00001528although they are not required. These are typically used for system programs
1529written in Python, such as a mail server's external command delivery program.
1530
1531.. note::
1532
1533 Some of these may not be available on all Unix platforms, since there is some
1534 variation. These constants are defined where they are defined by the underlying
1535 platform.
1536
1537
1538.. data:: EX_OK
1539
Benjamin Petersonf650e462010-05-06 23:03:05 +00001540 Exit code that means no error occurred.
1541
1542 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001543
Georg Brandl116aa622007-08-15 14:28:22 +00001544
1545.. data:: EX_USAGE
1546
1547 Exit code that means the command was used incorrectly, such as when the wrong
Benjamin Petersonf650e462010-05-06 23:03:05 +00001548 number of arguments are given.
1549
1550 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001551
Georg Brandl116aa622007-08-15 14:28:22 +00001552
1553.. data:: EX_DATAERR
1554
Benjamin Petersonf650e462010-05-06 23:03:05 +00001555 Exit code that means the input data was incorrect.
1556
1557 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001558
Georg Brandl116aa622007-08-15 14:28:22 +00001559
1560.. data:: EX_NOINPUT
1561
1562 Exit code that means an input file did not exist or was not readable.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001563
Georg Brandlc575c902008-09-13 17:46:05 +00001564 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001565
Georg Brandl116aa622007-08-15 14:28:22 +00001566
1567.. data:: EX_NOUSER
1568
Benjamin Petersonf650e462010-05-06 23:03:05 +00001569 Exit code that means a specified user did not exist.
1570
1571 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001572
Georg Brandl116aa622007-08-15 14:28:22 +00001573
1574.. data:: EX_NOHOST
1575
Benjamin Petersonf650e462010-05-06 23:03:05 +00001576 Exit code that means a specified host did not exist.
1577
1578 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001579
Georg Brandl116aa622007-08-15 14:28:22 +00001580
1581.. data:: EX_UNAVAILABLE
1582
Benjamin Petersonf650e462010-05-06 23:03:05 +00001583 Exit code that means that a required service is unavailable.
1584
1585 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001586
Georg Brandl116aa622007-08-15 14:28:22 +00001587
1588.. data:: EX_SOFTWARE
1589
Benjamin Petersonf650e462010-05-06 23:03:05 +00001590 Exit code that means an internal software error was detected.
1591
1592 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001593
Georg Brandl116aa622007-08-15 14:28:22 +00001594
1595.. data:: EX_OSERR
1596
1597 Exit code that means an operating system error was detected, such as the
Benjamin Petersonf650e462010-05-06 23:03:05 +00001598 inability to fork or create a pipe.
1599
1600 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001601
Georg Brandl116aa622007-08-15 14:28:22 +00001602
1603.. data:: EX_OSFILE
1604
1605 Exit code that means some system file did not exist, could not be opened, or had
Benjamin Petersonf650e462010-05-06 23:03:05 +00001606 some other kind of error.
1607
1608 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001609
Georg Brandl116aa622007-08-15 14:28:22 +00001610
1611.. data:: EX_CANTCREAT
1612
1613 Exit code that means a user specified output file could not be created.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001614
Georg Brandlc575c902008-09-13 17:46:05 +00001615 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001616
Georg Brandl116aa622007-08-15 14:28:22 +00001617
1618.. data:: EX_IOERR
1619
1620 Exit code that means that an error occurred while doing I/O on some file.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001621
Georg Brandlc575c902008-09-13 17:46:05 +00001622 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001623
Georg Brandl116aa622007-08-15 14:28:22 +00001624
1625.. data:: EX_TEMPFAIL
1626
1627 Exit code that means a temporary failure occurred. This indicates something
1628 that may not really be an error, such as a network connection that couldn't be
Benjamin Petersonf650e462010-05-06 23:03:05 +00001629 made during a retryable operation.
1630
1631 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001632
Georg Brandl116aa622007-08-15 14:28:22 +00001633
1634.. data:: EX_PROTOCOL
1635
1636 Exit code that means that a protocol exchange was illegal, invalid, or not
Benjamin Petersonf650e462010-05-06 23:03:05 +00001637 understood.
1638
1639 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001640
Georg Brandl116aa622007-08-15 14:28:22 +00001641
1642.. data:: EX_NOPERM
1643
1644 Exit code that means that there were insufficient permissions to perform the
Benjamin Petersonf650e462010-05-06 23:03:05 +00001645 operation (but not intended for file system problems).
1646
1647 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001648
Georg Brandl116aa622007-08-15 14:28:22 +00001649
1650.. data:: EX_CONFIG
1651
1652 Exit code that means that some kind of configuration error occurred.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001653
Georg Brandlc575c902008-09-13 17:46:05 +00001654 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001655
Georg Brandl116aa622007-08-15 14:28:22 +00001656
1657.. data:: EX_NOTFOUND
1658
Benjamin Petersonf650e462010-05-06 23:03:05 +00001659 Exit code that means something like "an entry was not found".
1660
1661 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001662
Georg Brandl116aa622007-08-15 14:28:22 +00001663
1664.. function:: fork()
1665
Christian Heimesfaf2f632008-01-06 16:59:19 +00001666 Fork a child process. Return ``0`` in the child and the child's process id in the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001667 parent. If an error occurs :exc:`OSError` is raised.
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +00001668
1669 Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
1670 known issues when using fork() from a thread.
1671
Georg Brandlc575c902008-09-13 17:46:05 +00001672 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001673
1674
1675.. function:: forkpty()
1676
1677 Fork a child process, using a new pseudo-terminal as the child's controlling
1678 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1679 new child's process id in the parent, and *fd* is the file descriptor of the
1680 master end of the pseudo-terminal. For a more portable approach, use the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001681 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001682
Georg Brandlc575c902008-09-13 17:46:05 +00001683 Availability: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001684
1685
1686.. function:: kill(pid, sig)
1687
1688 .. index::
1689 single: process; killing
1690 single: process; signalling
1691
1692 Send signal *sig* to the process *pid*. Constants for the specific signals
1693 available on the host platform are defined in the :mod:`signal` module.
Brian Curtineb24d742010-04-12 17:16:38 +00001694
1695 Windows: The :data:`signal.CTRL_C_EVENT` and
1696 :data:`signal.CTRL_BREAK_EVENT` signals are special signals which can
1697 only be sent to console processes which share a common console window,
1698 e.g., some subprocesses. Any other value for *sig* will cause the process
1699 to be unconditionally killed by the TerminateProcess API, and the exit code
1700 will be set to *sig*. The Windows version of :func:`kill` additionally takes
1701 process handles to be killed.
Georg Brandl116aa622007-08-15 14:28:22 +00001702
Brian Curtin904bd392010-04-20 15:28:06 +00001703 .. versionadded:: 3.2 Windows support
1704
Georg Brandl116aa622007-08-15 14:28:22 +00001705
1706.. function:: killpg(pgid, sig)
1707
1708 .. index::
1709 single: process; killing
1710 single: process; signalling
1711
Benjamin Petersonf650e462010-05-06 23:03:05 +00001712 Send the signal *sig* to the process group *pgid*.
1713
1714 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001715
Georg Brandl116aa622007-08-15 14:28:22 +00001716
1717.. function:: nice(increment)
1718
1719 Add *increment* to the process's "niceness". Return the new niceness.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001720
Georg Brandlc575c902008-09-13 17:46:05 +00001721 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001722
1723
1724.. function:: plock(op)
1725
1726 Lock program segments into memory. The value of *op* (defined in
Benjamin Petersonf650e462010-05-06 23:03:05 +00001727 ``<sys/lock.h>``) determines which segments are locked.
1728
1729 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001730
1731
1732.. function:: popen(...)
1733 :noindex:
1734
1735 Run child processes, returning opened pipes for communications. These functions
1736 are described in section :ref:`os-newstreams`.
1737
1738
1739.. function:: spawnl(mode, path, ...)
1740 spawnle(mode, path, ..., env)
1741 spawnlp(mode, file, ...)
1742 spawnlpe(mode, file, ..., env)
1743 spawnv(mode, path, args)
1744 spawnve(mode, path, args, env)
1745 spawnvp(mode, file, args)
1746 spawnvpe(mode, file, args, env)
1747
1748 Execute the program *path* in a new process.
1749
1750 (Note that the :mod:`subprocess` module provides more powerful facilities for
1751 spawning new processes and retrieving their results; using that module is
Benjamin Peterson87c8d872009-06-11 22:54:11 +00001752 preferable to using these functions. Check especially the
1753 :ref:`subprocess-replacements` section.)
Georg Brandl116aa622007-08-15 14:28:22 +00001754
Christian Heimesfaf2f632008-01-06 16:59:19 +00001755 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl116aa622007-08-15 14:28:22 +00001756 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1757 exits normally, or ``-signal``, where *signal* is the signal that killed the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001758 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl116aa622007-08-15 14:28:22 +00001759 be used with the :func:`waitpid` function.
1760
Christian Heimesfaf2f632008-01-06 16:59:19 +00001761 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1762 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001763 to work with if the number of parameters is fixed when the code is written; the
1764 individual parameters simply become additional parameters to the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001765 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl116aa622007-08-15 14:28:22 +00001766 parameters is variable, with the arguments being passed in a list or tuple as
1767 the *args* parameter. In either case, the arguments to the child process must
1768 start with the name of the command being run.
1769
Christian Heimesfaf2f632008-01-06 16:59:19 +00001770 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001771 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1772 :envvar:`PATH` environment variable to locate the program *file*. When the
1773 environment is being replaced (using one of the :func:`spawn\*e` variants,
1774 discussed in the next paragraph), the new environment is used as the source of
1775 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1776 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1777 :envvar:`PATH` variable to locate the executable; *path* must contain an
1778 appropriate absolute or relative path.
1779
1780 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001781 (note that these all end in "e"), the *env* parameter must be a mapping
Christian Heimesa342c012008-04-20 21:01:16 +00001782 which is used to define the environment variables for the new process (they are
1783 used instead of the current process' environment); the functions
Georg Brandl116aa622007-08-15 14:28:22 +00001784 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
Benjamin Petersond23f8222009-04-05 19:13:16 +00001785 the new process to inherit the environment of the current process. Note that
1786 keys and values in the *env* dictionary must be strings; invalid keys or
1787 values will cause the function to fail, with a return value of ``127``.
Georg Brandl116aa622007-08-15 14:28:22 +00001788
1789 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1790 equivalent::
1791
1792 import os
1793 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1794
1795 L = ['cp', 'index.html', '/dev/null']
1796 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1797
1798 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1799 and :func:`spawnvpe` are not available on Windows.
1800
Georg Brandl116aa622007-08-15 14:28:22 +00001801
1802.. data:: P_NOWAIT
1803 P_NOWAITO
1804
1805 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1806 functions. If either of these values is given, the :func:`spawn\*` functions
Christian Heimesfaf2f632008-01-06 16:59:19 +00001807 will return as soon as the new process has been created, with the process id as
Benjamin Petersonf650e462010-05-06 23:03:05 +00001808 the return value.
1809
1810 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001811
Georg Brandl116aa622007-08-15 14:28:22 +00001812
1813.. data:: P_WAIT
1814
1815 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1816 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1817 return until the new process has run to completion and will return the exit code
1818 of the process the run is successful, or ``-signal`` if a signal kills the
Benjamin Petersonf650e462010-05-06 23:03:05 +00001819 process.
1820
1821 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001822
Georg Brandl116aa622007-08-15 14:28:22 +00001823
1824.. data:: P_DETACH
1825 P_OVERLAY
1826
1827 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1828 functions. These are less portable than those listed above. :const:`P_DETACH`
1829 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1830 console of the calling process. If :const:`P_OVERLAY` is used, the current
1831 process will be replaced; the :func:`spawn\*` function will not return.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001832
Georg Brandl116aa622007-08-15 14:28:22 +00001833 Availability: Windows.
1834
Georg Brandl116aa622007-08-15 14:28:22 +00001835
1836.. function:: startfile(path[, operation])
1837
1838 Start a file with its associated application.
1839
1840 When *operation* is not specified or ``'open'``, this acts like double-clicking
1841 the file in Windows Explorer, or giving the file name as an argument to the
1842 :program:`start` command from the interactive command shell: the file is opened
1843 with whatever application (if any) its extension is associated.
1844
1845 When another *operation* is given, it must be a "command verb" that specifies
1846 what should be done with the file. Common verbs documented by Microsoft are
1847 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1848 ``'find'`` (to be used on directories).
1849
1850 :func:`startfile` returns as soon as the associated application is launched.
1851 There is no option to wait for the application to close, and no way to retrieve
1852 the application's exit status. The *path* parameter is relative to the current
1853 directory. If you want to use an absolute path, make sure the first character
1854 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1855 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
Benjamin Petersonf650e462010-05-06 23:03:05 +00001856 the path is properly encoded for Win32.
1857
1858 Availability: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001859
Georg Brandl116aa622007-08-15 14:28:22 +00001860
1861.. function:: system(command)
1862
1863 Execute the command (a string) in a subshell. This is implemented by calling
Georg Brandl495f7b52009-10-27 15:28:25 +00001864 the Standard C function :cfunc:`system`, and has the same limitations.
1865 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the
1866 executed command.
Georg Brandl116aa622007-08-15 14:28:22 +00001867
1868 On Unix, the return value is the exit status of the process encoded in the
1869 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1870 of the return value of the C :cfunc:`system` function, so the return value of
1871 the Python function is system-dependent.
1872
1873 On Windows, the return value is that returned by the system shell after running
1874 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1875 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1876 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1877 the command run; on systems using a non-native shell, consult your shell
1878 documentation.
1879
Georg Brandl116aa622007-08-15 14:28:22 +00001880 The :mod:`subprocess` module provides more powerful facilities for spawning new
1881 processes and retrieving their results; using that module is preferable to using
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001882 this function. Use the :mod:`subprocess` module. Check especially the
1883 :ref:`subprocess-replacements` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001884
Benjamin Petersonf650e462010-05-06 23:03:05 +00001885 Availability: Unix, Windows.
1886
Georg Brandl116aa622007-08-15 14:28:22 +00001887
1888.. function:: times()
1889
Benjamin Petersonf650e462010-05-06 23:03:05 +00001890 Return a 5-tuple of floating point numbers indicating accumulated (processor
1891 or other) times, in seconds. The items are: user time, system time,
1892 children's user time, children's system time, and elapsed real time since a
1893 fixed point in the past, in that order. See the Unix manual page
1894 :manpage:`times(2)` or the corresponding Windows Platform API documentation.
1895 On Windows, only the first two items are filled, the others are zero.
1896
1897 Availability: Unix, Windows
Georg Brandl116aa622007-08-15 14:28:22 +00001898
1899
1900.. function:: wait()
1901
1902 Wait for completion of a child process, and return a tuple containing its pid
1903 and exit status indication: a 16-bit number, whose low byte is the signal number
1904 that killed the process, and whose high byte is the exit status (if the signal
1905 number is zero); the high bit of the low byte is set if a core file was
Benjamin Petersonf650e462010-05-06 23:03:05 +00001906 produced.
1907
1908 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001909
1910
1911.. function:: waitpid(pid, options)
1912
1913 The details of this function differ on Unix and Windows.
1914
1915 On Unix: Wait for completion of a child process given by process id *pid*, and
1916 return a tuple containing its process id and exit status indication (encoded as
1917 for :func:`wait`). The semantics of the call are affected by the value of the
1918 integer *options*, which should be ``0`` for normal operation.
1919
1920 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1921 that specific process. If *pid* is ``0``, the request is for the status of any
1922 child in the process group of the current process. If *pid* is ``-1``, the
1923 request pertains to any child of the current process. If *pid* is less than
1924 ``-1``, status is requested for any process in the process group ``-pid`` (the
1925 absolute value of *pid*).
1926
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00001927 An :exc:`OSError` is raised with the value of errno when the syscall
1928 returns -1.
1929
Georg Brandl116aa622007-08-15 14:28:22 +00001930 On Windows: Wait for completion of a process given by process handle *pid*, and
1931 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1932 (shifting makes cross-platform use of the function easier). A *pid* less than or
1933 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1934 value of integer *options* has no effect. *pid* can refer to any process whose
1935 id is known, not necessarily a child process. The :func:`spawn` functions called
1936 with :const:`P_NOWAIT` return suitable process handles.
1937
1938
1939.. function:: wait3([options])
1940
1941 Similar to :func:`waitpid`, except no process id argument is given and a
1942 3-element tuple containing the child's process id, exit status indication, and
1943 resource usage information is returned. Refer to :mod:`resource`.\
1944 :func:`getrusage` for details on resource usage information. The option
1945 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001946
Georg Brandl116aa622007-08-15 14:28:22 +00001947 Availability: Unix.
1948
Georg Brandl116aa622007-08-15 14:28:22 +00001949
1950.. function:: wait4(pid, options)
1951
1952 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1953 process id, exit status indication, and resource usage information is returned.
1954 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1955 information. The arguments to :func:`wait4` are the same as those provided to
Benjamin Petersonf650e462010-05-06 23:03:05 +00001956 :func:`waitpid`.
1957
1958 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001959
Georg Brandl116aa622007-08-15 14:28:22 +00001960
1961.. data:: WNOHANG
1962
1963 The option for :func:`waitpid` to return immediately if no child process status
1964 is available immediately. The function returns ``(0, 0)`` in this case.
Benjamin Petersonf650e462010-05-06 23:03:05 +00001965
Georg Brandlc575c902008-09-13 17:46:05 +00001966 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001967
1968
1969.. data:: WCONTINUED
1970
1971 This option causes child processes to be reported if they have been continued
Benjamin Petersonf650e462010-05-06 23:03:05 +00001972 from a job control stop since their status was last reported.
1973
1974 Availability: Some Unix systems.
Georg Brandl116aa622007-08-15 14:28:22 +00001975
Georg Brandl116aa622007-08-15 14:28:22 +00001976
1977.. data:: WUNTRACED
1978
1979 This option causes child processes to be reported if they have been stopped but
Benjamin Petersonf650e462010-05-06 23:03:05 +00001980 their current state has not been reported since they were stopped.
1981
1982 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001983
Georg Brandl116aa622007-08-15 14:28:22 +00001984
1985The following functions take a process status code as returned by
1986:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1987used to determine the disposition of a process.
1988
Georg Brandl116aa622007-08-15 14:28:22 +00001989.. function:: WCOREDUMP(status)
1990
Christian Heimesfaf2f632008-01-06 16:59:19 +00001991 Return ``True`` if a core dump was generated for the process, otherwise
Benjamin Petersonf650e462010-05-06 23:03:05 +00001992 return ``False``.
1993
1994 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001995
Georg Brandl116aa622007-08-15 14:28:22 +00001996
1997.. function:: WIFCONTINUED(status)
1998
Christian Heimesfaf2f632008-01-06 16:59:19 +00001999 Return ``True`` if the process has been continued from a job control stop,
Benjamin Petersonf650e462010-05-06 23:03:05 +00002000 otherwise return ``False``.
2001
2002 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002003
Georg Brandl116aa622007-08-15 14:28:22 +00002004
2005.. function:: WIFSTOPPED(status)
2006
Christian Heimesfaf2f632008-01-06 16:59:19 +00002007 Return ``True`` if the process has been stopped, otherwise return
Benjamin Petersonf650e462010-05-06 23:03:05 +00002008 ``False``.
2009
2010 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002011
2012
2013.. function:: WIFSIGNALED(status)
2014
Christian Heimesfaf2f632008-01-06 16:59:19 +00002015 Return ``True`` if the process exited due to a signal, otherwise return
Benjamin Petersonf650e462010-05-06 23:03:05 +00002016 ``False``.
2017
2018 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002019
2020
2021.. function:: WIFEXITED(status)
2022
Christian Heimesfaf2f632008-01-06 16:59:19 +00002023 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
Benjamin Petersonf650e462010-05-06 23:03:05 +00002024 otherwise return ``False``.
2025
2026 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002027
2028
2029.. function:: WEXITSTATUS(status)
2030
2031 If ``WIFEXITED(status)`` is true, return the integer parameter to the
2032 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002033
Georg Brandlc575c902008-09-13 17:46:05 +00002034 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002035
2036
2037.. function:: WSTOPSIG(status)
2038
Benjamin Petersonf650e462010-05-06 23:03:05 +00002039 Return the signal which caused the process to stop.
2040
2041 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002042
2043
2044.. function:: WTERMSIG(status)
2045
Benjamin Petersonf650e462010-05-06 23:03:05 +00002046 Return the signal which caused the process to exit.
2047
2048 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002049
2050
2051.. _os-path:
2052
2053Miscellaneous System Information
2054--------------------------------
2055
2056
2057.. function:: confstr(name)
2058
2059 Return string-valued system configuration values. *name* specifies the
2060 configuration value to retrieve; it may be a string which is the name of a
2061 defined system value; these names are specified in a number of standards (POSIX,
2062 Unix 95, Unix 98, and others). Some platforms define additional names as well.
2063 The names known to the host operating system are given as the keys of the
2064 ``confstr_names`` dictionary. For configuration variables not included in that
Benjamin Petersonf650e462010-05-06 23:03:05 +00002065 mapping, passing an integer for *name* is also accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00002066
2067 If the configuration value specified by *name* isn't defined, ``None`` is
2068 returned.
2069
2070 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2071 specific value for *name* is not supported by the host system, even if it is
2072 included in ``confstr_names``, an :exc:`OSError` is raised with
2073 :const:`errno.EINVAL` for the error number.
2074
Benjamin Petersonf650e462010-05-06 23:03:05 +00002075 Availability: Unix
2076
Georg Brandl116aa622007-08-15 14:28:22 +00002077
2078.. data:: confstr_names
2079
2080 Dictionary mapping names accepted by :func:`confstr` to the integer values
2081 defined for those names by the host operating system. This can be used to
Benjamin Petersonf650e462010-05-06 23:03:05 +00002082 determine the set of names known to the system.
2083
2084 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002085
2086
2087.. function:: getloadavg()
2088
Christian Heimesa62da1d2008-01-12 19:39:10 +00002089 Return the number of processes in the system run queue averaged over the last
2090 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Benjamin Petersonf650e462010-05-06 23:03:05 +00002091 unobtainable.
2092
2093 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002094
Georg Brandl116aa622007-08-15 14:28:22 +00002095
2096.. function:: sysconf(name)
2097
2098 Return integer-valued system configuration values. If the configuration value
2099 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2100 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2101 provides information on the known names is given by ``sysconf_names``.
Benjamin Petersonf650e462010-05-06 23:03:05 +00002102
Georg Brandlc575c902008-09-13 17:46:05 +00002103 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002104
2105
2106.. data:: sysconf_names
2107
2108 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2109 defined for those names by the host operating system. This can be used to
Benjamin Petersonf650e462010-05-06 23:03:05 +00002110 determine the set of names known to the system.
2111
2112 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00002113
Christian Heimesfaf2f632008-01-06 16:59:19 +00002114The following data values are used to support path manipulation operations. These
Georg Brandl116aa622007-08-15 14:28:22 +00002115are defined for all platforms.
2116
2117Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2118
2119
2120.. data:: curdir
2121
2122 The constant string used by the operating system to refer to the current
Georg Brandlc575c902008-09-13 17:46:05 +00002123 directory. This is ``'.'`` for Windows and POSIX. Also available via
2124 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00002125
2126
2127.. data:: pardir
2128
2129 The constant string used by the operating system to refer to the parent
Georg Brandlc575c902008-09-13 17:46:05 +00002130 directory. This is ``'..'`` for Windows and POSIX. Also available via
2131 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00002132
2133
2134.. data:: sep
2135
Georg Brandlc575c902008-09-13 17:46:05 +00002136 The character used by the operating system to separate pathname components.
2137 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
2138 is not sufficient to be able to parse or concatenate pathnames --- use
Georg Brandl116aa622007-08-15 14:28:22 +00002139 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2140 useful. Also available via :mod:`os.path`.
2141
2142
2143.. data:: altsep
2144
2145 An alternative character used by the operating system to separate pathname
2146 components, or ``None`` if only one separator character exists. This is set to
2147 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2148 :mod:`os.path`.
2149
2150
2151.. data:: extsep
2152
2153 The character which separates the base filename from the extension; for example,
2154 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2155
Georg Brandl116aa622007-08-15 14:28:22 +00002156
2157.. data:: pathsep
2158
2159 The character conventionally used by the operating system to separate search
2160 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2161 Windows. Also available via :mod:`os.path`.
2162
2163
2164.. data:: defpath
2165
2166 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
2167 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
2168
2169
2170.. data:: linesep
2171
2172 The string used to separate (or, rather, terminate) lines on the current
Georg Brandlc575c902008-09-13 17:46:05 +00002173 platform. This may be a single character, such as ``'\n'`` for POSIX, or
2174 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
2175 *os.linesep* as a line terminator when writing files opened in text mode (the
2176 default); use a single ``'\n'`` instead, on all platforms.
Georg Brandl116aa622007-08-15 14:28:22 +00002177
2178
2179.. data:: devnull
2180
Georg Brandlc575c902008-09-13 17:46:05 +00002181 The file path of the null device. For example: ``'/dev/null'`` for POSIX.
2182 Also available via :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00002183
Georg Brandl116aa622007-08-15 14:28:22 +00002184
2185.. _os-miscfunc:
2186
2187Miscellaneous Functions
2188-----------------------
2189
2190
2191.. function:: urandom(n)
2192
2193 Return a string of *n* random bytes suitable for cryptographic use.
2194
2195 This function returns random bytes from an OS-specific randomness source. The
2196 returned data should be unpredictable enough for cryptographic applications,
2197 though its exact quality depends on the OS implementation. On a UNIX-like
2198 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
2199 If a randomness source is not found, :exc:`NotImplementedError` will be raised.