blob: 1bc91267ba9747038e959e275623cda71881be12 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`os` --- Miscellaneous operating system interfaces
2=======================================================
3
4.. module:: os
5 :synopsis: Miscellaneous operating system interfaces.
6
7
Georg Brandl57fe0f22008-01-12 10:53:29 +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 Brandl8ec7f652007-08-15 14:28:01 +000015
Georg Brandl953fe5f2010-03-21 19:06:51 +000016Notes on the availability of these functions:
Georg Brandl8ec7f652007-08-15 14:28:01 +000017
Georg Brandl953fe5f2010-03-21 19:06:51 +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 Brandl8ec7f652007-08-15 14:28:01 +000023
Georg Brandl953fe5f2010-03-21 19:06:51 +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 Brandl8ec7f652007-08-15 14:28:01 +000027
Georg Brandl953fe5f2010-03-21 19:06:51 +000028* An "Availability: Unix" note means that this function is commonly found on
29 Unix systems. It does not make any claims about its existence on a specific
30 operating system.
31
32* If not separately noted, all functions that claim "Availability: Unix" are
33 supported on Mac OS X, which builds on a Unix core.
Georg Brandl9af94982008-09-13 17:41:16 +000034
Benjamin Peterson2f9134b2010-05-06 23:04:44 +000035.. Availability notes get their own line and occur at the end of the function
36.. documentation.
37
Georg Brandl9af94982008-09-13 17:41:16 +000038.. note::
39
Georg Brandl57fe0f22008-01-12 10:53:29 +000040 All functions in this module raise :exc:`OSError` in the case of invalid or
41 inaccessible file names and paths, or other arguments that have the correct
42 type, but are not accepted by the operating system.
Georg Brandl8ec7f652007-08-15 14:28:01 +000043
Georg Brandl8ec7f652007-08-15 14:28:01 +000044
45.. exception:: error
46
Georg Brandl57fe0f22008-01-12 10:53:29 +000047 An alias for the built-in :exc:`OSError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +000048
49
50.. data:: name
51
Georg Brandl953fe5f2010-03-21 19:06:51 +000052 The name of the operating system dependent module imported. The following
53 names have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``,
54 ``'os2'``, ``'ce'``, ``'java'``, ``'riscos'``.
Georg Brandl8ec7f652007-08-15 14:28:01 +000055
56
Georg Brandl8ec7f652007-08-15 14:28:01 +000057.. _os-procinfo:
58
59Process Parameters
60------------------
61
62These functions and data items provide information and operate on the current
63process and user.
64
65
66.. data:: environ
67
68 A mapping object representing the string environment. For example,
69 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
70 and is equivalent to ``getenv("HOME")`` in C.
71
72 This mapping is captured the first time the :mod:`os` module is imported,
73 typically during Python startup as part of processing :file:`site.py`. Changes
74 to the environment made after this time are not reflected in ``os.environ``,
75 except for changes made by modifying ``os.environ`` directly.
76
77 If the platform supports the :func:`putenv` function, this mapping may be used
78 to modify the environment as well as query the environment. :func:`putenv` will
79 be called automatically when the mapping is modified.
80
81 .. note::
82
83 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
84 to modify ``os.environ``.
85
86 .. note::
87
Georg Brandl9af94982008-09-13 17:41:16 +000088 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
89 cause memory leaks. Refer to the system documentation for
90 :cfunc:`putenv`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000091
92 If :func:`putenv` is not provided, a modified copy of this mapping may be
93 passed to the appropriate process-creation functions to cause child processes
94 to use a modified environment.
95
Georg Brandl4a212682007-09-20 17:57:59 +000096 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl8ec7f652007-08-15 14:28:01 +000097 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl4a212682007-09-20 17:57:59 +000098 automatically when an item is deleted from ``os.environ``, and when
Georg Brandl1a94ec22007-10-24 21:40:38 +000099 one of the :meth:`pop` or :meth:`clear` methods is called.
Georg Brandl4a212682007-09-20 17:57:59 +0000100
101 .. versionchanged:: 2.6
Georg Brandl1a94ec22007-10-24 21:40:38 +0000102 Also unset environment variables when calling :meth:`os.environ.clear`
103 and :meth:`os.environ.pop`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000104
105
106.. function:: chdir(path)
107 fchdir(fd)
108 getcwd()
109 :noindex:
110
111 These functions are described in :ref:`os-file-dir`.
112
113
114.. function:: ctermid()
115
116 Return the filename corresponding to the controlling terminal of the process.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000117
Georg Brandl8ec7f652007-08-15 14:28:01 +0000118 Availability: Unix.
119
120
121.. function:: getegid()
122
123 Return the effective group id of the current process. This corresponds to the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000124 "set id" bit on the file being executed in the current process.
125
126 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
128
129.. function:: geteuid()
130
131 .. index:: single: user; effective id
132
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000133 Return the current process's effective user id.
134
135 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000136
137
138.. function:: getgid()
139
140 .. index:: single: process; group
141
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000142 Return the real group id of the current process.
143
144 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000145
146
147.. function:: getgroups()
148
149 Return list of supplemental group ids associated with the current process.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000150
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151 Availability: Unix.
152
153
154.. function:: getlogin()
155
156 Return the name of the user logged in on the controlling terminal of the
157 process. For most purposes, it is more useful to use the environment variable
158 :envvar:`LOGNAME` to find out who the user is, or
159 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000160 effective user id.
161
162 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000163
164
165.. function:: getpgid(pid)
166
167 Return the process group id of the process with process id *pid*. If *pid* is 0,
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000168 the process group id of the current process is returned.
169
170 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171
172 .. versionadded:: 2.3
173
174
175.. function:: getpgrp()
176
177 .. index:: single: process; group
178
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000179 Return the id of the current process group.
180
181 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
183
184.. function:: getpid()
185
186 .. index:: single: process; id
187
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000188 Return the current process id.
189
190 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000191
192
193.. function:: getppid()
194
195 .. index:: single: process; id of parent
196
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000197 Return the parent's process id.
198
199 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000200
201
202.. function:: getuid()
203
204 .. index:: single: user; id
205
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000206 Return the current process's user id.
207
208 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000209
210
211.. function:: getenv(varname[, value])
212
213 Return the value of the environment variable *varname* if it exists, or *value*
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000214 if it doesn't. *value* defaults to ``None``.
215
216 Availability: most flavors of Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000217
218
219.. function:: putenv(varname, value)
220
221 .. index:: single: environment variables; setting
222
223 Set the environment variable named *varname* to the string *value*. Such
224 changes to the environment affect subprocesses started with :func:`os.system`,
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000225 :func:`popen` or :func:`fork` and :func:`execv`.
226
227 Availability: most flavors of Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000228
229 .. note::
230
Georg Brandl9af94982008-09-13 17:41:16 +0000231 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
232 cause memory leaks. Refer to the system documentation for putenv.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000233
234 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
235 automatically translated into corresponding calls to :func:`putenv`; however,
236 calls to :func:`putenv` don't update ``os.environ``, so it is actually
237 preferable to assign to items of ``os.environ``.
238
239
240.. function:: setegid(egid)
241
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000242 Set the current process's effective group id.
243
244 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000245
246
247.. function:: seteuid(euid)
248
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000249 Set the current process's effective user id.
250
251 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000252
253
254.. function:: setgid(gid)
255
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000256 Set the current process' group id.
257
258 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259
260
261.. function:: setgroups(groups)
262
263 Set the list of supplemental group ids associated with the current process to
264 *groups*. *groups* must be a sequence, and each element must be an integer
Georg Brandlf725b952008-01-05 19:44:22 +0000265 identifying a group. This operation is typically available only to the superuser.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000266
Georg Brandl8ec7f652007-08-15 14:28:01 +0000267 Availability: Unix.
268
269 .. versionadded:: 2.2
270
271
272.. function:: setpgrp()
273
Georg Brandlf725b952008-01-05 19:44:22 +0000274 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
Georg Brandl8ec7f652007-08-15 14:28:01 +0000275 which version is implemented (if any). See the Unix manual for the semantics.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000276
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277 Availability: Unix.
278
279
280.. function:: setpgid(pid, pgrp)
281
Georg Brandlf725b952008-01-05 19:44:22 +0000282 Call the system call :cfunc:`setpgid` to set the process group id of the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283 process with id *pid* to the process group with id *pgrp*. See the Unix manual
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000284 for the semantics.
285
286 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000287
288
289.. function:: setreuid(ruid, euid)
290
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000291 Set the current process's real and effective user ids.
292
293 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000294
295
296.. function:: setregid(rgid, egid)
297
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000298 Set the current process's real and effective group ids.
299
300 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000301
302
303.. function:: getsid(pid)
304
Georg Brandlf725b952008-01-05 19:44:22 +0000305 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000306
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307 Availability: Unix.
308
309 .. versionadded:: 2.4
310
311
312.. function:: setsid()
313
Georg Brandlf725b952008-01-05 19:44:22 +0000314 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000315
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316 Availability: Unix.
317
318
319.. function:: setuid(uid)
320
321 .. index:: single: user; id, setting
322
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000323 Set the current process's user id.
324
325 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000326
Georg Brandl8ec7f652007-08-15 14:28:01 +0000327
Georg Brandlb19be572007-12-29 10:57:00 +0000328.. placed in this section since it relates to errno.... a little weak
Georg Brandl8ec7f652007-08-15 14:28:01 +0000329.. function:: strerror(code)
330
331 Return the error message corresponding to the error code in *code*.
Georg Brandl3fc974f2008-05-11 21:16:37 +0000332 On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000333 error number, :exc:`ValueError` is raised.
334
335 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336
337
338.. function:: umask(mask)
339
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000340 Set the current numeric umask and return the previous umask.
341
342 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343
344
345.. function:: uname()
346
347 .. index::
348 single: gethostname() (in module socket)
349 single: gethostbyaddr() (in module socket)
350
351 Return a 5-tuple containing information identifying the current operating
352 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
353 machine)``. Some systems truncate the nodename to 8 characters or to the
354 leading component; a better way to get the hostname is
355 :func:`socket.gethostname` or even
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000356 ``socket.gethostbyaddr(socket.gethostname())``.
357
358 Availability: recent flavors of Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000359
360
361.. function:: unsetenv(varname)
362
363 .. index:: single: environment variables; deleting
364
365 Unset (delete) the environment variable named *varname*. Such changes to the
366 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000367 :func:`fork` and :func:`execv`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000368
369 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
370 automatically translated into a corresponding call to :func:`unsetenv`; however,
371 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
372 preferable to delete items of ``os.environ``.
373
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000374 Availability: most flavors of Unix, Windows.
375
Georg Brandl8ec7f652007-08-15 14:28:01 +0000376
377.. _os-newstreams:
378
379File Object Creation
380--------------------
381
382These functions create new file objects. (See also :func:`open`.)
383
384
385.. function:: fdopen(fd[, mode[, bufsize]])
386
387 .. index:: single: I/O control; buffering
388
389 Return an open file object connected to the file descriptor *fd*. The *mode*
390 and *bufsize* arguments have the same meaning as the corresponding arguments to
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000391 the built-in :func:`open` function.
392
393 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000394
395 .. versionchanged:: 2.3
396 When specified, the *mode* argument must now start with one of the letters
397 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
398
399 .. versionchanged:: 2.5
400 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
401 set on the file descriptor (which the :cfunc:`fdopen` implementation already
402 does on most platforms).
403
404
405.. function:: popen(command[, mode[, bufsize]])
406
407 Open a pipe to or from *command*. The return value is an open file object
408 connected to the pipe, which can be read or written depending on whether *mode*
409 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
410 the corresponding argument to the built-in :func:`open` function. The exit
411 status of the command (encoded in the format specified for :func:`wait`) is
Georg Brandle081eef2009-05-26 09:04:23 +0000412 available as the return value of the :meth:`~file.close` method of the file object,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000413 except that when the exit status is zero (termination without errors), ``None``
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000414 is returned.
415
416 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000417
418 .. deprecated:: 2.6
Georg Brandl734373c2009-01-03 21:55:17 +0000419 This function is obsolete. Use the :mod:`subprocess` module. Check
Georg Brandl0ba92b22008-06-22 09:05:29 +0000420 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000421
422 .. versionchanged:: 2.0
423 This function worked unreliably under Windows in earlier versions of Python.
424 This was due to the use of the :cfunc:`_popen` function from the libraries
425 provided with Windows. Newer versions of Python do not use the broken
426 implementation from the Windows libraries.
427
428
429.. function:: tmpfile()
430
431 Return a new file object opened in update mode (``w+b``). The file has no
432 directory entries associated with it and will be automatically deleted once
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000433 there are no file descriptors for the file.
434
435 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000436
437There are a number of different :func:`popen\*` functions that provide slightly
438different ways to create subprocesses.
439
440.. deprecated:: 2.6
441 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
442 module.
443
444For each of the :func:`popen\*` variants, if *bufsize* is specified, it
445specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
446string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
447file objects should be opened in binary or text mode. The default value for
448*mode* is ``'t'``.
449
450Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
451case arguments will be passed directly to the program without shell intervention
452(as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
453(as with :func:`os.system`).
454
455These methods do not make it possible to retrieve the exit status from the child
456processes. The only way to control the input and output streams and also
457retrieve the return codes is to use the :mod:`subprocess` module; these are only
458available on Unix.
459
460For a discussion of possible deadlock conditions related to the use of these
461functions, see :ref:`popen2-flow-control`.
462
463
464.. function:: popen2(cmd[, mode[, bufsize]])
465
Georg Brandlf725b952008-01-05 19:44:22 +0000466 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000467 child_stdout)``.
468
469 .. deprecated:: 2.6
Georg Brandl734373c2009-01-03 21:55:17 +0000470 This function is obsolete. Use the :mod:`subprocess` module. Check
Georg Brandl0ba92b22008-06-22 09:05:29 +0000471 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000472
Georg Brandl9af94982008-09-13 17:41:16 +0000473 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000474
475 .. versionadded:: 2.0
476
477
478.. function:: popen3(cmd[, mode[, bufsize]])
479
Georg Brandlf725b952008-01-05 19:44:22 +0000480 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000481 child_stdout, child_stderr)``.
482
483 .. deprecated:: 2.6
Georg Brandl734373c2009-01-03 21:55:17 +0000484 This function is obsolete. Use the :mod:`subprocess` module. Check
Georg Brandl0ba92b22008-06-22 09:05:29 +0000485 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000486
Georg Brandl9af94982008-09-13 17:41:16 +0000487 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000488
489 .. versionadded:: 2.0
490
491
492.. function:: popen4(cmd[, mode[, bufsize]])
493
Georg Brandlf725b952008-01-05 19:44:22 +0000494 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000495 child_stdout_and_stderr)``.
496
497 .. deprecated:: 2.6
Georg Brandl734373c2009-01-03 21:55:17 +0000498 This function is obsolete. Use the :mod:`subprocess` module. Check
Georg Brandl0ba92b22008-06-22 09:05:29 +0000499 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000500
Georg Brandl9af94982008-09-13 17:41:16 +0000501 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502
503 .. versionadded:: 2.0
504
505(Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
506point of view of the child process, so *child_stdin* is the child's standard
507input.)
508
509This functionality is also available in the :mod:`popen2` module using functions
510of the same names, but the return values of those functions have a different
511order.
512
513
514.. _os-fd-ops:
515
516File Descriptor Operations
517--------------------------
518
519These functions operate on I/O streams referenced using file descriptors.
520
521File descriptors are small integers corresponding to a file that has been opened
522by the current process. For example, standard input is usually file descriptor
5230, standard output is 1, and standard error is 2. Further files opened by a
524process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
525is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
526by file descriptors.
527
Georg Brandl324086f2010-05-18 23:13:04 +0000528The :meth:`~file.fileno` method can be used to obtain the file descriptor
529associated with a file object when required. Note that using the file
530descriptor directly will bypass the file object methods, ignoring aspects such
531as internal buffering of data.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000532
533.. function:: close(fd)
534
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000535 Close file descriptor *fd*.
536
537 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000538
539 .. note::
540
541 This function is intended for low-level I/O and must be applied to a file
Georg Brandle081eef2009-05-26 09:04:23 +0000542 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543 object" returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandle081eef2009-05-26 09:04:23 +0000544 :func:`fdopen`, use its :meth:`~file.close` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000545
546
Georg Brandl309501a2008-01-19 20:22:13 +0000547.. function:: closerange(fd_low, fd_high)
548
549 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000550 ignoring errors. Equivalent to::
Georg Brandl309501a2008-01-19 20:22:13 +0000551
552 for fd in xrange(fd_low, fd_high):
553 try:
554 os.close(fd)
555 except OSError:
556 pass
557
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000558 Availability: Unix, Windows.
559
Georg Brandl309501a2008-01-19 20:22:13 +0000560 .. versionadded:: 2.6
561
562
Georg Brandl8ec7f652007-08-15 14:28:01 +0000563.. function:: dup(fd)
564
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000565 Return a duplicate of file descriptor *fd*.
566
567 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000568
569
570.. function:: dup2(fd, fd2)
571
572 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000573
Georg Brandl9af94982008-09-13 17:41:16 +0000574 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000575
576
Christian Heimes36281872007-11-30 21:11:28 +0000577.. function:: fchmod(fd, mode)
578
579 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000580 for :func:`chmod` for possible values of *mode*.
581
582 Availability: Unix.
Christian Heimes36281872007-11-30 21:11:28 +0000583
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000584 .. versionadded:: 2.6
585
Christian Heimes36281872007-11-30 21:11:28 +0000586
587.. function:: fchown(fd, uid, gid)
588
589 Change the owner and group id of the file given by *fd* to the numeric *uid*
590 and *gid*. To leave one of the ids unchanged, set it to -1.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000591
Christian Heimes36281872007-11-30 21:11:28 +0000592 Availability: Unix.
593
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000594 .. versionadded:: 2.6
595
Christian Heimes36281872007-11-30 21:11:28 +0000596
Georg Brandl8ec7f652007-08-15 14:28:01 +0000597.. function:: fdatasync(fd)
598
599 Force write of file with filedescriptor *fd* to disk. Does not force update of
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000600 metadata.
601
602 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000603
Georg Brandla3c242c2009-10-27 14:19:50 +0000604 .. note::
605 This function is not available on MacOS.
606
Georg Brandl8ec7f652007-08-15 14:28:01 +0000607
608.. function:: fpathconf(fd, name)
609
610 Return system configuration information relevant to an open file. *name*
611 specifies the configuration value to retrieve; it may be a string which is the
612 name of a defined system value; these names are specified in a number of
613 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
614 additional names as well. The names known to the host operating system are
615 given in the ``pathconf_names`` dictionary. For configuration variables not
616 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000617
618 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
619 specific value for *name* is not supported by the host system, even if it is
620 included in ``pathconf_names``, an :exc:`OSError` is raised with
621 :const:`errno.EINVAL` for the error number.
622
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000623 Availability: Unix.
624
Georg Brandl8ec7f652007-08-15 14:28:01 +0000625
626.. function:: fstat(fd)
627
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000628 Return status for file descriptor *fd*, like :func:`stat`.
629
630 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000631
632
633.. function:: fstatvfs(fd)
634
635 Return information about the filesystem containing the file associated with file
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000636 descriptor *fd*, like :func:`statvfs`.
637
638 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000639
640
641.. function:: fsync(fd)
642
643 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
644 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
645
646 If you're starting with a Python file object *f*, first do ``f.flush()``, and
647 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000648 with *f* are written to disk.
649
650 Availability: Unix, and Windows starting in 2.2.3.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000651
652
653.. function:: ftruncate(fd, length)
654
655 Truncate the file corresponding to file descriptor *fd*, so that it is at most
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000656 *length* bytes in size.
657
658 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000659
660
661.. function:: isatty(fd)
662
663 Return ``True`` if the file descriptor *fd* is open and connected to a
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000664 tty(-like) device, else ``False``.
665
666 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000667
668
669.. function:: lseek(fd, pos, how)
670
Georg Brandlf725b952008-01-05 19:44:22 +0000671 Set the current position of file descriptor *fd* to position *pos*, modified
672 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
673 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
674 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000675 the file.
676
677 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678
679
680.. function:: open(file, flags[, mode])
681
682 Open the file *file* and set various flags according to *flags* and possibly its
683 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
684 current umask value is first masked out. Return the file descriptor for the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000685 newly opened file.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000686
687 For a description of the flag and mode values, see the C run-time documentation;
688 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
689 this module too (see below).
690
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000691 Availability: Unix, Windows.
692
Georg Brandl8ec7f652007-08-15 14:28:01 +0000693 .. note::
694
Georg Brandl0dfdf002009-10-27 14:36:50 +0000695 This function is intended for low-level I/O. For normal usage, use the
696 built-in function :func:`open`, which returns a "file object" with
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000697 :meth:`~file.read` and :meth:`~file.wprite` methods (and many more). To
Georg Brandl0dfdf002009-10-27 14:36:50 +0000698 wrap a file descriptor in a "file object", use :func:`fdopen`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000699
700
701.. function:: openpty()
702
703 .. index:: module: pty
704
705 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
706 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000707 approach, use the :mod:`pty` module.
708
709 Availability: some flavors of Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000710
711
712.. function:: pipe()
713
714 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000715 and writing, respectively.
716
717 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000718
719
720.. function:: read(fd, n)
721
722 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
723 bytes read. If the end of the file referred to by *fd* has been reached, an
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000724 empty string is returned.
725
726 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000727
728 .. note::
729
730 This function is intended for low-level I/O and must be applied to a file
Georg Brandle081eef2009-05-26 09:04:23 +0000731 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a "file object"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000732 returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandle081eef2009-05-26 09:04:23 +0000733 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
734 :meth:`~file.readline` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000735
736
737.. function:: tcgetpgrp(fd)
738
739 Return the process group associated with the terminal given by *fd* (an open
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000740 file descriptor as returned by :func:`os.open`).
741
742 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000743
744
745.. function:: tcsetpgrp(fd, pg)
746
747 Set the process group associated with the terminal given by *fd* (an open file
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000748 descriptor as returned by :func:`os.open`) to *pg*.
749
750 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751
752
753.. function:: ttyname(fd)
754
755 Return a string which specifies the terminal device associated with
Georg Brandlbb75e4e2007-10-21 10:46:24 +0000756 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000757 exception is raised.
758
759 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000760
761
762.. function:: write(fd, str)
763
764 Write the string *str* to file descriptor *fd*. Return the number of bytes
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000765 actually written.
766
767 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000768
769 .. note::
770
771 This function is intended for low-level I/O and must be applied to a file
Georg Brandle081eef2009-05-26 09:04:23 +0000772 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
Georg Brandl8ec7f652007-08-15 14:28:01 +0000773 object" returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandle081eef2009-05-26 09:04:23 +0000774 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
775 :meth:`~file.write` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000776
Georg Brandlfa71a902008-12-05 09:08:28 +0000777The following constants are options for the *flags* parameter to the
Georg Brandle081eef2009-05-26 09:04:23 +0000778:func:`~os.open` function. They can be combined using the bitwise OR operator
Georg Brandlfa71a902008-12-05 09:08:28 +0000779``|``. Some of them are not available on all platforms. For descriptions of
Georg Brandlf3a0b862008-12-07 14:47:12 +0000780their availability and use, consult the :manpage:`open(2)` manual page on Unix
Doug Hellmann0108ed32009-09-20 20:55:04 +0000781or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000782
783
784.. data:: O_RDONLY
785 O_WRONLY
786 O_RDWR
787 O_APPEND
788 O_CREAT
789 O_EXCL
790 O_TRUNC
791
Georg Brandlfa71a902008-12-05 09:08:28 +0000792 These constants are available on Unix and Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000793
794
795.. data:: O_DSYNC
796 O_RSYNC
797 O_SYNC
798 O_NDELAY
799 O_NONBLOCK
800 O_NOCTTY
801 O_SHLOCK
802 O_EXLOCK
803
Georg Brandlfa71a902008-12-05 09:08:28 +0000804 These constants are only available on Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000805
806
807.. data:: O_BINARY
Georg Brandlb67da6e2007-11-24 13:56:09 +0000808 O_NOINHERIT
Georg Brandl8ec7f652007-08-15 14:28:01 +0000809 O_SHORT_LIVED
810 O_TEMPORARY
811 O_RANDOM
812 O_SEQUENTIAL
813 O_TEXT
814
Georg Brandlfa71a902008-12-05 09:08:28 +0000815 These constants are only available on Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000816
817
Georg Brandlae6b9f32008-05-16 13:41:26 +0000818.. data:: O_ASYNC
819 O_DIRECT
Georg Brandlb67da6e2007-11-24 13:56:09 +0000820 O_DIRECTORY
821 O_NOFOLLOW
822 O_NOATIME
823
Georg Brandlfa71a902008-12-05 09:08:28 +0000824 These constants are GNU extensions and not present if they are not defined by
825 the C library.
Georg Brandlb67da6e2007-11-24 13:56:09 +0000826
827
Georg Brandl8ec7f652007-08-15 14:28:01 +0000828.. data:: SEEK_SET
829 SEEK_CUR
830 SEEK_END
831
832 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
Georg Brandl9af94982008-09-13 17:41:16 +0000833 respectively. Availability: Windows, Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000834
835 .. versionadded:: 2.5
836
837
838.. _os-file-dir:
839
840Files and Directories
841---------------------
842
Georg Brandl8ec7f652007-08-15 14:28:01 +0000843.. function:: access(path, mode)
844
845 Use the real uid/gid to test for access to *path*. Note that most operations
846 will use the effective uid/gid, therefore this routine can be used in a
847 suid/sgid environment to test if the invoking user has the specified access to
848 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
849 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
850 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
851 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000852 information.
853
854 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000855
856 .. note::
857
Georg Brandl0dfdf002009-10-27 14:36:50 +0000858 Using :func:`access` to check if a user is authorized to e.g. open a file
859 before actually doing so using :func:`open` creates a security hole,
860 because the user might exploit the short time interval between checking
861 and opening the file to manipulate it.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000862
863 .. note::
864
865 I/O operations may fail even when :func:`access` indicates that they would
866 succeed, particularly for operations on network filesystems which may have
867 permissions semantics beyond the usual POSIX permission-bit model.
868
869
870.. data:: F_OK
871
872 Value to pass as the *mode* parameter of :func:`access` to test the existence of
873 *path*.
874
875
876.. data:: R_OK
877
878 Value to include in the *mode* parameter of :func:`access` to test the
879 readability of *path*.
880
881
882.. data:: W_OK
883
884 Value to include in the *mode* parameter of :func:`access` to test the
885 writability of *path*.
886
887
888.. data:: X_OK
889
890 Value to include in the *mode* parameter of :func:`access` to determine if
891 *path* can be executed.
892
893
894.. function:: chdir(path)
895
896 .. index:: single: directory; changing
897
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000898 Change the current working directory to *path*.
899
900 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000901
902
903.. function:: fchdir(fd)
904
905 Change the current working directory to the directory represented by the file
906 descriptor *fd*. The descriptor must refer to an opened directory, not an open
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000907 file.
908
909 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000910
911 .. versionadded:: 2.3
912
913
914.. function:: getcwd()
915
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000916 Return a string representing the current working directory.
917
918 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000919
920
921.. function:: getcwdu()
922
923 Return a Unicode object representing the current working directory.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000924
Georg Brandl9af94982008-09-13 17:41:16 +0000925 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000926
927 .. versionadded:: 2.3
928
929
930.. function:: chflags(path, flags)
931
932 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
933 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
934
935 * ``UF_NODUMP``
936 * ``UF_IMMUTABLE``
937 * ``UF_APPEND``
938 * ``UF_OPAQUE``
939 * ``UF_NOUNLINK``
940 * ``SF_ARCHIVED``
941 * ``SF_IMMUTABLE``
942 * ``SF_APPEND``
943 * ``SF_NOUNLINK``
944 * ``SF_SNAPSHOT``
945
Georg Brandl9af94982008-09-13 17:41:16 +0000946 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000947
948 .. versionadded:: 2.6
949
950
951.. function:: chroot(path)
952
953 Change the root directory of the current process to *path*. Availability:
Georg Brandl9af94982008-09-13 17:41:16 +0000954 Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000955
956 .. versionadded:: 2.2
957
958
959.. function:: chmod(path, mode)
960
961 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Georg Brandlf725b952008-01-05 19:44:22 +0000962 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl8ec7f652007-08-15 14:28:01 +0000963 combinations of them:
964
965
R. David Murrayba2c2b12009-07-21 14:23:11 +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 Brandl8ec7f652007-08-15 14:28:01 +0000985
Georg Brandl9af94982008-09-13 17:41:16 +0000986 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Peterson2f9134b2010-05-06 23:04:44 +0000999 one of the ids unchanged, set it to -1.
1000
1001 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Peterson2f9134b2010-05-06 23:04:44 +00001007 follow symbolic links.
1008
1009 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001010
1011 .. versionadded:: 2.6
1012
1013
Georg Brandl81ddc1a2007-11-30 22:04:45 +00001014.. function:: lchmod(path, mode)
1015
1016 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
1017 affects the symlink rather than the target. See the docs for :func:`chmod`
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001018 for possible values of *mode*.
1019
1020 Availability: Unix.
Georg Brandl81ddc1a2007-11-30 22:04:45 +00001021
1022 .. versionadded:: 2.6
1023
1024
Georg Brandl8ec7f652007-08-15 14:28:01 +00001025.. function:: lchown(path, uid, gid)
1026
Georg Brandlf725b952008-01-05 19:44:22 +00001027 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001028 function will not follow symbolic links.
1029
1030 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001031
1032 .. versionadded:: 2.3
1033
1034
Georg Brandl78559542009-10-27 14:03:07 +00001035.. function:: link(source, link_name)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001036
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001037 Create a hard link pointing to *source* named *link_name*.
1038
1039 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040
1041
1042.. function:: listdir(path)
1043
Georg Brandld2094602008-12-05 08:51:30 +00001044 Return a list containing the names of the entries in the directory given by
1045 *path*. The list is in arbitrary order. It does not include the special
1046 entries ``'.'`` and ``'..'`` even if they are present in the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001047 directory.
1048
1049 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001050
1051 .. versionchanged:: 2.3
1052 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
Georg Brandle081eef2009-05-26 09:04:23 +00001053 a list of Unicode objects. Undecodable filenames will still be returned as
1054 string objects.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001055
1056
1057.. function:: lstat(path)
1058
Georg Brandl03b15c62007-11-01 17:19:33 +00001059 Like :func:`stat`, but do not follow symbolic links. This is an alias for
1060 :func:`stat` on platforms that do not support symbolic links, such as
1061 Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001062
1063
1064.. function:: mkfifo(path[, mode])
1065
1066 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
1067 *mode* is ``0666`` (octal). The current umask value is first masked out from
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001068 the mode.
1069
1070 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001071
1072 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
1073 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
1074 rendezvous between "client" and "server" type processes: the server opens the
1075 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
1076 doesn't open the FIFO --- it just creates the rendezvous point.
1077
1078
1079.. function:: mknod(filename[, mode=0600, device])
1080
1081 Create a filesystem node (file, device special file or named pipe) named
1082 *filename*. *mode* specifies both the permissions to use and the type of node to
1083 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
1084 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
1085 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
1086 For ``stat.S_IFCHR`` and
1087 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
1088 :func:`os.makedev`), otherwise it is ignored.
1089
1090 .. versionadded:: 2.3
1091
1092
1093.. function:: major(device)
1094
Georg Brandlf725b952008-01-05 19:44:22 +00001095 Extract the device major number from a raw device number (usually the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001096 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
1097
1098 .. versionadded:: 2.3
1099
1100
1101.. function:: minor(device)
1102
Georg Brandlf725b952008-01-05 19:44:22 +00001103 Extract the device minor number from a raw device number (usually the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001104 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
1105
1106 .. versionadded:: 2.3
1107
1108
1109.. function:: makedev(major, minor)
1110
Georg Brandlf725b952008-01-05 19:44:22 +00001111 Compose a raw device number from the major and minor device numbers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001112
1113 .. versionadded:: 2.3
1114
1115
1116.. function:: mkdir(path[, mode])
1117
1118 Create a directory named *path* with numeric mode *mode*. The default *mode* is
1119 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001120 current umask value is first masked out.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001121
Mark Summerfieldac3d4292007-11-02 08:24:59 +00001122 It is also possible to create temporary directories; see the
1123 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1124
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001125 Availability: Unix, Windows.
1126
Georg Brandl8ec7f652007-08-15 14:28:01 +00001127
1128.. function:: makedirs(path[, mode])
1129
1130 .. index::
1131 single: directory; creating
1132 single: UNC paths; and os.makedirs()
1133
1134 Recursive directory creation function. Like :func:`mkdir`, but makes all
1135 intermediate-level directories needed to contain the leaf directory. Throws an
1136 :exc:`error` exception if the leaf directory already exists or cannot be
1137 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
1138 ignored. Where it is used, the current umask value is first masked out.
1139
1140 .. note::
1141
1142 :func:`makedirs` will become confused if the path elements to create include
Georg Brandlf725b952008-01-05 19:44:22 +00001143 :data:`os.pardir`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001144
1145 .. versionadded:: 1.5.2
1146
1147 .. versionchanged:: 2.3
1148 This function now handles UNC paths correctly.
1149
1150
1151.. function:: pathconf(path, name)
1152
1153 Return system configuration information relevant to a named file. *name*
1154 specifies the configuration value to retrieve; it may be a string which is the
1155 name of a defined system value; these names are specified in a number of
1156 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1157 additional names as well. The names known to the host operating system are
1158 given in the ``pathconf_names`` dictionary. For configuration variables not
1159 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001160
1161 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1162 specific value for *name* is not supported by the host system, even if it is
1163 included in ``pathconf_names``, an :exc:`OSError` is raised with
1164 :const:`errno.EINVAL` for the error number.
1165
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001166 Availability: Unix.
1167
Georg Brandl8ec7f652007-08-15 14:28:01 +00001168
1169.. data:: pathconf_names
1170
1171 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1172 the integer values defined for those names by the host operating system. This
1173 can be used to determine the set of names known to the system. Availability:
Georg Brandl9af94982008-09-13 17:41:16 +00001174 Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001175
1176
1177.. function:: readlink(path)
1178
1179 Return a string representing the path to which the symbolic link points. The
1180 result may be either an absolute or relative pathname; if it is relative, it may
1181 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1182 result)``.
1183
1184 .. versionchanged:: 2.6
1185 If the *path* is a Unicode object the result will also be a Unicode object.
1186
Georg Brandl9af94982008-09-13 17:41:16 +00001187 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001188
1189
1190.. function:: remove(path)
1191
Georg Brandl5be70d42009-10-27 14:50:20 +00001192 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
1193 raised; see :func:`rmdir` below to remove a directory. This is identical to
1194 the :func:`unlink` function documented below. On Windows, attempting to
1195 remove a file that is in use causes an exception to be raised; on Unix, the
1196 directory entry is removed but the storage allocated to the file is not made
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001197 available until the original file is no longer in use.
1198
1199 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001200
1201
1202.. function:: removedirs(path)
1203
1204 .. index:: single: directory; deleting
1205
Georg Brandlf725b952008-01-05 19:44:22 +00001206 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001207 leaf directory is successfully removed, :func:`removedirs` tries to
1208 successively remove every parent directory mentioned in *path* until an error
1209 is raised (which is ignored, because it generally means that a parent directory
1210 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1211 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1212 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1213 successfully removed.
1214
1215 .. versionadded:: 1.5.2
1216
1217
1218.. function:: rename(src, dst)
1219
1220 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1221 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Georg Brandlf725b952008-01-05 19:44:22 +00001222 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl8ec7f652007-08-15 14:28:01 +00001223 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1224 the renaming will be an atomic operation (this is a POSIX requirement). On
1225 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1226 file; there may be no way to implement an atomic rename when *dst* names an
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001227 existing file.
1228
1229 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001230
1231
1232.. function:: renames(old, new)
1233
1234 Recursive directory or file renaming function. Works like :func:`rename`, except
1235 creation of any intermediate directories needed to make the new pathname good is
1236 attempted first. After the rename, directories corresponding to rightmost path
1237 segments of the old name will be pruned away using :func:`removedirs`.
1238
1239 .. versionadded:: 1.5.2
1240
1241 .. note::
1242
1243 This function can fail with the new directory structure made if you lack
1244 permissions needed to remove the leaf directory or file.
1245
1246
1247.. function:: rmdir(path)
1248
Georg Brandl5be70d42009-10-27 14:50:20 +00001249 Remove (delete) the directory *path*. Only works when the directory is
1250 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001251 directory trees, :func:`shutil.rmtree` can be used.
1252
1253 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001254
1255
1256.. function:: stat(path)
1257
1258 Perform a :cfunc:`stat` system call on the given path. The return value is an
1259 object whose attributes correspond to the members of the :ctype:`stat`
1260 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1261 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
Georg Brandlf725b952008-01-05 19:44:22 +00001262 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
Georg Brandl8ec7f652007-08-15 14:28:01 +00001263 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1264 access), :attr:`st_mtime` (time of most recent content modification),
1265 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1266 Unix, or the time of creation on Windows)::
1267
1268 >>> import os
1269 >>> statinfo = os.stat('somefile.txt')
1270 >>> statinfo
1271 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1272 >>> statinfo.st_size
1273 926L
1274 >>>
1275
1276 .. versionchanged:: 2.3
Georg Brandlf725b952008-01-05 19:44:22 +00001277 If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
Georg Brandl8ec7f652007-08-15 14:28:01 +00001278 seconds. Fractions of a second may be reported if the system supports that. On
1279 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1280 discussion.
1281
1282 On some Unix systems (such as Linux), the following attributes may also be
1283 available: :attr:`st_blocks` (number of blocks allocated for file),
1284 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1285 inode device). :attr:`st_flags` (user defined flags for file).
1286
1287 On other Unix systems (such as FreeBSD), the following attributes may be
1288 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1289 (file generation number), :attr:`st_birthtime` (time of file creation).
1290
1291 On Mac OS systems, the following attributes may also be available:
1292 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1293
1294 On RISCOS systems, the following attributes are also available: :attr:`st_ftype`
1295 (file type), :attr:`st_attrs` (attributes), :attr:`st_obtype` (object type).
1296
1297 .. index:: module: stat
1298
1299 For backward compatibility, the return value of :func:`stat` is also accessible
1300 as a tuple of at least 10 integers giving the most important (and portable)
1301 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1302 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1303 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1304 :attr:`st_ctime`. More items may be added at the end by some implementations.
1305 The standard module :mod:`stat` defines functions and constants that are useful
1306 for extracting information from a :ctype:`stat` structure. (On Windows, some
1307 items are filled with dummy values.)
1308
1309 .. note::
1310
1311 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1312 :attr:`st_ctime` members depends on the operating system and the file system.
1313 For example, on Windows systems using the FAT or FAT32 file systems,
1314 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1315 resolution. See your operating system documentation for details.
1316
Georg Brandl9af94982008-09-13 17:41:16 +00001317 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001318
1319 .. versionchanged:: 2.2
1320 Added access to values as attributes of the returned object.
1321
1322 .. versionchanged:: 2.5
Georg Brandlf725b952008-01-05 19:44:22 +00001323 Added :attr:`st_gen` and :attr:`st_birthtime`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001324
1325
1326.. function:: stat_float_times([newvalue])
1327
1328 Determine whether :class:`stat_result` represents time stamps as float objects.
1329 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1330 ``False``, future calls return ints. If *newvalue* is omitted, return the
1331 current setting.
1332
1333 For compatibility with older Python versions, accessing :class:`stat_result` as
1334 a tuple always returns integers.
1335
1336 .. versionchanged:: 2.5
1337 Python now returns float values by default. Applications which do not work
1338 correctly with floating point time stamps can use this function to restore the
1339 old behaviour.
1340
1341 The resolution of the timestamps (that is the smallest possible fraction)
1342 depends on the system. Some systems only support second resolution; on these
1343 systems, the fraction will always be zero.
1344
1345 It is recommended that this setting is only changed at program startup time in
1346 the *__main__* module; libraries should never change this setting. If an
1347 application uses a library that works incorrectly if floating point time stamps
1348 are processed, this application should turn the feature off until the library
1349 has been corrected.
1350
1351
1352.. function:: statvfs(path)
1353
1354 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1355 an object whose attributes describe the filesystem on the given path, and
1356 correspond to the members of the :ctype:`statvfs` structure, namely:
1357 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1358 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001359 :attr:`f_flag`, :attr:`f_namemax`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001360
1361 .. index:: module: statvfs
1362
1363 For backward compatibility, the return value is also accessible as a tuple whose
1364 values correspond to the attributes, in the order given above. The standard
1365 module :mod:`statvfs` defines constants that are useful for extracting
1366 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1367 this remains useful when writing code that needs to work with versions of Python
1368 that don't support accessing the fields as attributes.
1369
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001370 Availability: Unix.
1371
Georg Brandl8ec7f652007-08-15 14:28:01 +00001372 .. versionchanged:: 2.2
1373 Added access to values as attributes of the returned object.
1374
1375
Georg Brandl78559542009-10-27 14:03:07 +00001376.. function:: symlink(source, link_name)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001377
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001378 Create a symbolic link pointing to *source* named *link_name*.
1379
1380 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001381
1382
1383.. function:: tempnam([dir[, prefix]])
1384
1385 Return a unique path name that is reasonable for creating a temporary file.
1386 This will be an absolute path that names a potential directory entry in the
1387 directory *dir* or a common location for temporary files if *dir* is omitted or
1388 ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
1389 to the filename. Applications are responsible for properly creating and
1390 managing files created using paths returned by :func:`tempnam`; no automatic
1391 cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
Georg Brandlf725b952008-01-05 19:44:22 +00001392 overrides *dir*, while on Windows :envvar:`TMP` is used. The specific
Georg Brandl8ec7f652007-08-15 14:28:01 +00001393 behavior of this function depends on the C library implementation; some aspects
1394 are underspecified in system documentation.
1395
1396 .. warning::
1397
1398 Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1399 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1400
Georg Brandl9af94982008-09-13 17:41:16 +00001401 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001402
1403
1404.. function:: tmpnam()
1405
1406 Return a unique path name that is reasonable for creating a temporary file.
1407 This will be an absolute path that names a potential directory entry in a common
1408 location for temporary files. Applications are responsible for properly
1409 creating and managing files created using paths returned by :func:`tmpnam`; no
1410 automatic cleanup is provided.
1411
1412 .. warning::
1413
1414 Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1415 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1416
1417 Availability: Unix, Windows. This function probably shouldn't be used on
1418 Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1419 name in the root directory of the current drive, and that's generally a poor
1420 location for a temp file (depending on privileges, you may not even be able to
1421 open a file using this name).
1422
1423
1424.. data:: TMP_MAX
1425
1426 The maximum number of unique names that :func:`tmpnam` will generate before
1427 reusing names.
1428
1429
1430.. function:: unlink(path)
1431
Georg Brandl5be70d42009-10-27 14:50:20 +00001432 Remove (delete) the file *path*. This is the same function as
1433 :func:`remove`; the :func:`unlink` name is its traditional Unix
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001434 name.
1435
1436 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001437
1438
1439.. function:: utime(path, times)
1440
Benjamin Peterson5b02ef32008-08-16 03:13:07 +00001441 Set the access and modified times of the file specified by *path*. If *times*
1442 is ``None``, then the file's access and modified times are set to the current
1443 time. (The effect is similar to running the Unix program :program:`touch` on
1444 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1445 ``(atime, mtime)`` which is used to set the access and modified times,
1446 respectively. Whether a directory can be given for *path* depends on whether
1447 the operating system implements directories as files (for example, Windows
1448 does not). Note that the exact times you set here may not be returned by a
1449 subsequent :func:`stat` call, depending on the resolution with which your
1450 operating system records access and modification times; see :func:`stat`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001451
1452 .. versionchanged:: 2.0
1453 Added support for ``None`` for *times*.
1454
Georg Brandl9af94982008-09-13 17:41:16 +00001455 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001456
1457
1458.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1459
1460 .. index::
1461 single: directory; walking
1462 single: directory; traversal
1463
Georg Brandlf725b952008-01-05 19:44:22 +00001464 Generate the file names in a directory tree by walking the tree
1465 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl8ec7f652007-08-15 14:28:01 +00001466 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1467 filenames)``.
1468
1469 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1470 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1471 *filenames* is a list of the names of the non-directory files in *dirpath*.
1472 Note that the names in the lists contain no path components. To get a full path
1473 (which begins with *top*) to a file or directory in *dirpath*, do
1474 ``os.path.join(dirpath, name)``.
1475
Georg Brandlf725b952008-01-05 19:44:22 +00001476 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001477 directory is generated before the triples for any of its subdirectories
Georg Brandlf725b952008-01-05 19:44:22 +00001478 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001479 directory is generated after the triples for all of its subdirectories
Georg Brandlf725b952008-01-05 19:44:22 +00001480 (directories are generated bottom-up).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001481
Georg Brandlf725b952008-01-05 19:44:22 +00001482 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl8ec7f652007-08-15 14:28:01 +00001483 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1484 recurse into the subdirectories whose names remain in *dirnames*; this can be
1485 used to prune the search, impose a specific order of visiting, or even to inform
1486 :func:`walk` about directories the caller creates or renames before it resumes
Georg Brandlf725b952008-01-05 19:44:22 +00001487 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001488 ineffective, because in bottom-up mode the directories in *dirnames* are
1489 generated before *dirpath* itself is generated.
1490
Georg Brandlf725b952008-01-05 19:44:22 +00001491 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl8ec7f652007-08-15 14:28:01 +00001492 argument *onerror* is specified, it should be a function; it will be called with
1493 one argument, an :exc:`OSError` instance. It can report the error to continue
1494 with the walk, or raise the exception to abort the walk. Note that the filename
1495 is available as the ``filename`` attribute of the exception object.
1496
1497 By default, :func:`walk` will not walk down into symbolic links that resolve to
Georg Brandlf725b952008-01-05 19:44:22 +00001498 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl8ec7f652007-08-15 14:28:01 +00001499 symlinks, on systems that support them.
1500
1501 .. versionadded:: 2.6
1502 The *followlinks* parameter.
1503
1504 .. note::
1505
Georg Brandlf725b952008-01-05 19:44:22 +00001506 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001507 link points to a parent directory of itself. :func:`walk` does not keep track of
1508 the directories it visited already.
1509
1510 .. note::
1511
1512 If you pass a relative pathname, don't change the current working directory
1513 between resumptions of :func:`walk`. :func:`walk` never changes the current
1514 directory, and assumes that its caller doesn't either.
1515
1516 This example displays the number of bytes taken by non-directory files in each
1517 directory under the starting directory, except that it doesn't look under any
1518 CVS subdirectory::
1519
1520 import os
1521 from os.path import join, getsize
1522 for root, dirs, files in os.walk('python/Lib/email'):
1523 print root, "consumes",
1524 print sum(getsize(join(root, name)) for name in files),
1525 print "bytes in", len(files), "non-directory files"
1526 if 'CVS' in dirs:
1527 dirs.remove('CVS') # don't visit CVS directories
1528
Georg Brandlf725b952008-01-05 19:44:22 +00001529 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001530 doesn't allow deleting a directory before the directory is empty::
1531
Georg Brandlf725b952008-01-05 19:44:22 +00001532 # Delete everything reachable from the directory named in "top",
Georg Brandl8ec7f652007-08-15 14:28:01 +00001533 # assuming there are no symbolic links.
1534 # CAUTION: This is dangerous! For example, if top == '/', it
1535 # could delete all your disk files.
1536 import os
1537 for root, dirs, files in os.walk(top, topdown=False):
1538 for name in files:
1539 os.remove(os.path.join(root, name))
1540 for name in dirs:
1541 os.rmdir(os.path.join(root, name))
1542
1543 .. versionadded:: 2.3
1544
1545
1546.. _os-process:
1547
1548Process Management
1549------------------
1550
1551These functions may be used to create and manage processes.
1552
1553The various :func:`exec\*` functions take a list of arguments for the new
1554program loaded into the process. In each case, the first of these arguments is
1555passed to the new program as its own name rather than as an argument a user may
1556have typed on a command line. For the C programmer, this is the ``argv[0]``
1557passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1558['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1559to be ignored.
1560
1561
1562.. function:: abort()
1563
1564 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1565 behavior is to produce a core dump; on Windows, the process immediately returns
1566 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1567 to register a handler for :const:`SIGABRT` will behave differently.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001568
Georg Brandl9af94982008-09-13 17:41:16 +00001569 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001570
1571
1572.. function:: execl(path, arg0, arg1, ...)
1573 execle(path, arg0, arg1, ..., env)
1574 execlp(file, arg0, arg1, ...)
1575 execlpe(file, arg0, arg1, ..., env)
1576 execv(path, args)
1577 execve(path, args, env)
1578 execvp(file, args)
1579 execvpe(file, args, env)
1580
1581 These functions all execute a new program, replacing the current process; they
1582 do not return. On Unix, the new executable is loaded into the current process,
Georg Brandlf725b952008-01-05 19:44:22 +00001583 and will have the same process id as the caller. Errors will be reported as
Georg Brandl734373c2009-01-03 21:55:17 +00001584 :exc:`OSError` exceptions.
Andrew M. Kuchlingac771662008-09-28 00:15:27 +00001585
1586 The current process is replaced immediately. Open file objects and
1587 descriptors are not flushed, so if there may be data buffered
1588 on these open files, you should flush them using
1589 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
1590 :func:`exec\*` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001591
Georg Brandlf725b952008-01-05 19:44:22 +00001592 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1593 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl8ec7f652007-08-15 14:28:01 +00001594 to work with if the number of parameters is fixed when the code is written; the
1595 individual parameters simply become additional parameters to the :func:`execl\*`
Georg Brandlf725b952008-01-05 19:44:22 +00001596 functions. The "v" variants are good when the number of parameters is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001597 variable, with the arguments being passed in a list or tuple as the *args*
1598 parameter. In either case, the arguments to the child process should start with
1599 the name of the command being run, but this is not enforced.
1600
Georg Brandlf725b952008-01-05 19:44:22 +00001601 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001602 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1603 :envvar:`PATH` environment variable to locate the program *file*. When the
1604 environment is being replaced (using one of the :func:`exec\*e` variants,
1605 discussed in the next paragraph), the new environment is used as the source of
1606 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1607 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1608 locate the executable; *path* must contain an appropriate absolute or relative
1609 path.
1610
1611 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Georg Brandlf725b952008-01-05 19:44:22 +00001612 that these all end in "e"), the *env* parameter must be a mapping which is
Georg Brandlfb246c42008-04-19 16:58:28 +00001613 used to define the environment variables for the new process (these are used
1614 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001615 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
Georg Brandl734373c2009-01-03 21:55:17 +00001616 inherit the environment of the current process.
Andrew M. Kuchlingac771662008-09-28 00:15:27 +00001617
1618 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001619
1620
1621.. function:: _exit(n)
1622
1623 Exit to the system with status *n*, without calling cleanup handlers, flushing
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001624 stdio buffers, etc.
1625
1626 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001627
1628 .. note::
1629
1630 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1631 be used in the child process after a :func:`fork`.
1632
Georg Brandlf725b952008-01-05 19:44:22 +00001633The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001634although they are not required. These are typically used for system programs
1635written in Python, such as a mail server's external command delivery program.
1636
1637.. note::
1638
1639 Some of these may not be available on all Unix platforms, since there is some
1640 variation. These constants are defined where they are defined by the underlying
1641 platform.
1642
1643
1644.. data:: EX_OK
1645
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001646 Exit code that means no error occurred.
1647
1648 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001649
1650 .. versionadded:: 2.3
1651
1652
1653.. data:: EX_USAGE
1654
1655 Exit code that means the command was used incorrectly, such as when the wrong
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001656 number of arguments are given.
1657
1658 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001659
1660 .. versionadded:: 2.3
1661
1662
1663.. data:: EX_DATAERR
1664
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001665 Exit code that means the input data was incorrect.
1666
1667 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001668
1669 .. versionadded:: 2.3
1670
1671
1672.. data:: EX_NOINPUT
1673
1674 Exit code that means an input file did not exist or was not readable.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001675
Georg Brandl9af94982008-09-13 17:41:16 +00001676 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001677
1678 .. versionadded:: 2.3
1679
1680
1681.. data:: EX_NOUSER
1682
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001683 Exit code that means a specified user did not exist.
1684
1685 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001686
1687 .. versionadded:: 2.3
1688
1689
1690.. data:: EX_NOHOST
1691
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001692 Exit code that means a specified host did not exist.
1693
1694 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001695
1696 .. versionadded:: 2.3
1697
1698
1699.. data:: EX_UNAVAILABLE
1700
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001701 Exit code that means that a required service is unavailable.
1702
1703 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001704
1705 .. versionadded:: 2.3
1706
1707
1708.. data:: EX_SOFTWARE
1709
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001710 Exit code that means an internal software error was detected.
1711
1712 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001713
1714 .. versionadded:: 2.3
1715
1716
1717.. data:: EX_OSERR
1718
1719 Exit code that means an operating system error was detected, such as the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001720 inability to fork or create a pipe.
1721
1722 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001723
1724 .. versionadded:: 2.3
1725
1726
1727.. data:: EX_OSFILE
1728
1729 Exit code that means some system file did not exist, could not be opened, or had
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001730 some other kind of error.
1731
1732 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001733
1734 .. versionadded:: 2.3
1735
1736
1737.. data:: EX_CANTCREAT
1738
1739 Exit code that means a user specified output file could not be created.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001740
Georg Brandl9af94982008-09-13 17:41:16 +00001741 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001742
1743 .. versionadded:: 2.3
1744
1745
1746.. data:: EX_IOERR
1747
1748 Exit code that means that an error occurred while doing I/O on some file.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001749
Georg Brandl9af94982008-09-13 17:41:16 +00001750 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001751
1752 .. versionadded:: 2.3
1753
1754
1755.. data:: EX_TEMPFAIL
1756
1757 Exit code that means a temporary failure occurred. This indicates something
1758 that may not really be an error, such as a network connection that couldn't be
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001759 made during a retryable operation.
1760
1761 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001762
1763 .. versionadded:: 2.3
1764
1765
1766.. data:: EX_PROTOCOL
1767
1768 Exit code that means that a protocol exchange was illegal, invalid, or not
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001769 understood.
1770
1771 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001772
1773 .. versionadded:: 2.3
1774
1775
1776.. data:: EX_NOPERM
1777
1778 Exit code that means that there were insufficient permissions to perform the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001779 operation (but not intended for file system problems).
1780
1781 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001782
1783 .. versionadded:: 2.3
1784
1785
1786.. data:: EX_CONFIG
1787
1788 Exit code that means that some kind of configuration error occurred.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001789
Georg Brandl9af94982008-09-13 17:41:16 +00001790 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001791
1792 .. versionadded:: 2.3
1793
1794
1795.. data:: EX_NOTFOUND
1796
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001797 Exit code that means something like "an entry was not found".
1798
1799 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001800
1801 .. versionadded:: 2.3
1802
1803
1804.. function:: fork()
1805
Georg Brandlf725b952008-01-05 19:44:22 +00001806 Fork a child process. Return ``0`` in the child and the child's process id in the
Skip Montanaro75e51682008-03-15 02:32:49 +00001807 parent. If an error occurs :exc:`OSError` is raised.
Gregory P. Smith08067492008-09-30 20:41:13 +00001808
1809 Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
1810 known issues when using fork() from a thread.
1811
Georg Brandl9af94982008-09-13 17:41:16 +00001812 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001813
1814
1815.. function:: forkpty()
1816
1817 Fork a child process, using a new pseudo-terminal as the child's controlling
1818 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1819 new child's process id in the parent, and *fd* is the file descriptor of the
1820 master end of the pseudo-terminal. For a more portable approach, use the
Skip Montanaro75e51682008-03-15 02:32:49 +00001821 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001822
Georg Brandl9af94982008-09-13 17:41:16 +00001823 Availability: some flavors of Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001824
1825
1826.. function:: kill(pid, sig)
1827
1828 .. index::
1829 single: process; killing
1830 single: process; signalling
1831
1832 Send signal *sig* to the process *pid*. Constants for the specific signals
1833 available on the host platform are defined in the :mod:`signal` module.
Georg Brandl9af94982008-09-13 17:41:16 +00001834 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001835
1836
1837.. function:: killpg(pgid, sig)
1838
1839 .. index::
1840 single: process; killing
1841 single: process; signalling
1842
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001843 Send the signal *sig* to the process group *pgid*.
1844
1845 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001846
1847 .. versionadded:: 2.3
1848
1849
1850.. function:: nice(increment)
1851
1852 Add *increment* to the process's "niceness". Return the new niceness.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001853
Georg Brandl9af94982008-09-13 17:41:16 +00001854 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001855
1856
1857.. function:: plock(op)
1858
1859 Lock program segments into memory. The value of *op* (defined in
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001860 ``<sys/lock.h>``) determines which segments are locked.
1861
1862 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001863
1864
1865.. function:: popen(...)
1866 popen2(...)
1867 popen3(...)
1868 popen4(...)
1869 :noindex:
1870
1871 Run child processes, returning opened pipes for communications. These functions
1872 are described in section :ref:`os-newstreams`.
1873
1874
1875.. function:: spawnl(mode, path, ...)
1876 spawnle(mode, path, ..., env)
1877 spawnlp(mode, file, ...)
1878 spawnlpe(mode, file, ..., env)
1879 spawnv(mode, path, args)
1880 spawnve(mode, path, args, env)
1881 spawnvp(mode, file, args)
1882 spawnvpe(mode, file, args, env)
1883
1884 Execute the program *path* in a new process.
1885
1886 (Note that the :mod:`subprocess` module provides more powerful facilities for
1887 spawning new processes and retrieving their results; using that module is
R. David Murray9f8a51c2009-06-25 17:40:52 +00001888 preferable to using these functions. Check especially the
1889 :ref:`subprocess-replacements` section.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001890
Georg Brandlf725b952008-01-05 19:44:22 +00001891 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl8ec7f652007-08-15 14:28:01 +00001892 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1893 exits normally, or ``-signal``, where *signal* is the signal that killed the
Georg Brandlf725b952008-01-05 19:44:22 +00001894 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl8ec7f652007-08-15 14:28:01 +00001895 be used with the :func:`waitpid` function.
1896
Georg Brandlf725b952008-01-05 19:44:22 +00001897 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1898 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl8ec7f652007-08-15 14:28:01 +00001899 to work with if the number of parameters is fixed when the code is written; the
1900 individual parameters simply become additional parameters to the
Georg Brandlf725b952008-01-05 19:44:22 +00001901 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl8ec7f652007-08-15 14:28:01 +00001902 parameters is variable, with the arguments being passed in a list or tuple as
1903 the *args* parameter. In either case, the arguments to the child process must
1904 start with the name of the command being run.
1905
Georg Brandlf725b952008-01-05 19:44:22 +00001906 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001907 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1908 :envvar:`PATH` environment variable to locate the program *file*. When the
1909 environment is being replaced (using one of the :func:`spawn\*e` variants,
1910 discussed in the next paragraph), the new environment is used as the source of
1911 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1912 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1913 :envvar:`PATH` variable to locate the executable; *path* must contain an
1914 appropriate absolute or relative path.
1915
1916 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Georg Brandlf725b952008-01-05 19:44:22 +00001917 (note that these all end in "e"), the *env* parameter must be a mapping
Georg Brandlfb246c42008-04-19 16:58:28 +00001918 which is used to define the environment variables for the new process (they are
1919 used instead of the current process' environment); the functions
Georg Brandl8ec7f652007-08-15 14:28:01 +00001920 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
Georg Brandl8943caf2009-04-05 21:11:43 +00001921 the new process to inherit the environment of the current process. Note that
1922 keys and values in the *env* dictionary must be strings; invalid keys or
1923 values will cause the function to fail, with a return value of ``127``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001924
1925 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1926 equivalent::
1927
1928 import os
1929 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1930
1931 L = ['cp', 'index.html', '/dev/null']
1932 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1933
1934 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1935 and :func:`spawnvpe` are not available on Windows.
1936
1937 .. versionadded:: 1.6
1938
1939
1940.. data:: P_NOWAIT
1941 P_NOWAITO
1942
1943 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1944 functions. If either of these values is given, the :func:`spawn\*` functions
Georg Brandlf725b952008-01-05 19:44:22 +00001945 will return as soon as the new process has been created, with the process id as
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001946 the return value.
1947
1948 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001949
1950 .. versionadded:: 1.6
1951
1952
1953.. data:: P_WAIT
1954
1955 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1956 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1957 return until the new process has run to completion and will return the exit code
1958 of the process the run is successful, or ``-signal`` if a signal kills the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001959 process.
1960
1961 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001962
1963 .. versionadded:: 1.6
1964
1965
1966.. data:: P_DETACH
1967 P_OVERLAY
1968
1969 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1970 functions. These are less portable than those listed above. :const:`P_DETACH`
1971 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1972 console of the calling process. If :const:`P_OVERLAY` is used, the current
1973 process will be replaced; the :func:`spawn\*` function will not return.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001974
Georg Brandl8ec7f652007-08-15 14:28:01 +00001975 Availability: Windows.
1976
1977 .. versionadded:: 1.6
1978
1979
1980.. function:: startfile(path[, operation])
1981
1982 Start a file with its associated application.
1983
1984 When *operation* is not specified or ``'open'``, this acts like double-clicking
1985 the file in Windows Explorer, or giving the file name as an argument to the
1986 :program:`start` command from the interactive command shell: the file is opened
1987 with whatever application (if any) its extension is associated.
1988
1989 When another *operation* is given, it must be a "command verb" that specifies
1990 what should be done with the file. Common verbs documented by Microsoft are
1991 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1992 ``'find'`` (to be used on directories).
1993
1994 :func:`startfile` returns as soon as the associated application is launched.
1995 There is no option to wait for the application to close, and no way to retrieve
1996 the application's exit status. The *path* parameter is relative to the current
1997 directory. If you want to use an absolute path, make sure the first character
1998 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1999 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002000 the path is properly encoded for Win32.
2001
2002 Availability: Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002003
2004 .. versionadded:: 2.0
2005
2006 .. versionadded:: 2.5
2007 The *operation* parameter.
2008
2009
2010.. function:: system(command)
2011
2012 Execute the command (a string) in a subshell. This is implemented by calling
Georg Brandl5d2eb342009-10-27 15:08:27 +00002013 the Standard C function :cfunc:`system`, and has the same limitations.
2014 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the
2015 executed command.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002016
2017 On Unix, the return value is the exit status of the process encoded in the
2018 format specified for :func:`wait`. Note that POSIX does not specify the meaning
2019 of the return value of the C :cfunc:`system` function, so the return value of
2020 the Python function is system-dependent.
2021
2022 On Windows, the return value is that returned by the system shell after running
2023 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
2024 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
2025 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
2026 the command run; on systems using a non-native shell, consult your shell
2027 documentation.
2028
Georg Brandl8ec7f652007-08-15 14:28:01 +00002029 The :mod:`subprocess` module provides more powerful facilities for spawning new
2030 processes and retrieving their results; using that module is preferable to using
Georg Brandl0ba92b22008-06-22 09:05:29 +00002031 this function. Use the :mod:`subprocess` module. Check especially the
2032 :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002033
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002034 Availability: Unix, Windows.
2035
Georg Brandl8ec7f652007-08-15 14:28:01 +00002036
2037.. function:: times()
2038
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002039 Return a 5-tuple of floating point numbers indicating accumulated (processor
2040 or other) times, in seconds. The items are: user time, system time,
2041 children's user time, children's system time, and elapsed real time since a
2042 fixed point in the past, in that order. See the Unix manual page
2043 :manpage:`times(2)` or the corresponding Windows Platform API documentation.
2044 On Windows, only the first two items are filled, the others are zero.
2045
2046 Availability: Unix, Windows
Georg Brandl8ec7f652007-08-15 14:28:01 +00002047
2048
2049.. function:: wait()
2050
2051 Wait for completion of a child process, and return a tuple containing its pid
2052 and exit status indication: a 16-bit number, whose low byte is the signal number
2053 that killed the process, and whose high byte is the exit status (if the signal
2054 number is zero); the high bit of the low byte is set if a core file was
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002055 produced.
2056
2057 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002058
2059
2060.. function:: waitpid(pid, options)
2061
2062 The details of this function differ on Unix and Windows.
2063
2064 On Unix: Wait for completion of a child process given by process id *pid*, and
2065 return a tuple containing its process id and exit status indication (encoded as
2066 for :func:`wait`). The semantics of the call are affected by the value of the
2067 integer *options*, which should be ``0`` for normal operation.
2068
2069 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
2070 that specific process. If *pid* is ``0``, the request is for the status of any
2071 child in the process group of the current process. If *pid* is ``-1``, the
2072 request pertains to any child of the current process. If *pid* is less than
2073 ``-1``, status is requested for any process in the process group ``-pid`` (the
2074 absolute value of *pid*).
2075
Gregory P. Smith59de7f52008-08-15 23:14:00 +00002076 An :exc:`OSError` is raised with the value of errno when the syscall
2077 returns -1.
2078
Georg Brandl8ec7f652007-08-15 14:28:01 +00002079 On Windows: Wait for completion of a process given by process handle *pid*, and
2080 return a tuple containing *pid*, and its exit status shifted left by 8 bits
2081 (shifting makes cross-platform use of the function easier). A *pid* less than or
2082 equal to ``0`` has no special meaning on Windows, and raises an exception. The
2083 value of integer *options* has no effect. *pid* can refer to any process whose
2084 id is known, not necessarily a child process. The :func:`spawn` functions called
2085 with :const:`P_NOWAIT` return suitable process handles.
2086
2087
2088.. function:: wait3([options])
2089
2090 Similar to :func:`waitpid`, except no process id argument is given and a
2091 3-element tuple containing the child's process id, exit status indication, and
2092 resource usage information is returned. Refer to :mod:`resource`.\
2093 :func:`getrusage` for details on resource usage information. The option
2094 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002095
Georg Brandl8ec7f652007-08-15 14:28:01 +00002096 Availability: Unix.
2097
2098 .. versionadded:: 2.5
2099
2100
2101.. function:: wait4(pid, options)
2102
2103 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
2104 process id, exit status indication, and resource usage information is returned.
2105 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
2106 information. The arguments to :func:`wait4` are the same as those provided to
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002107 :func:`waitpid`.
2108
2109 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002110
2111 .. versionadded:: 2.5
2112
2113
2114.. data:: WNOHANG
2115
2116 The option for :func:`waitpid` to return immediately if no child process status
2117 is available immediately. The function returns ``(0, 0)`` in this case.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002118
Georg Brandl9af94982008-09-13 17:41:16 +00002119 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002120
2121
2122.. data:: WCONTINUED
2123
2124 This option causes child processes to be reported if they have been continued
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002125 from a job control stop since their status was last reported.
2126
2127 Availability: Some Unix systems.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002128
2129 .. versionadded:: 2.3
2130
2131
2132.. data:: WUNTRACED
2133
2134 This option causes child processes to be reported if they have been stopped but
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002135 their current state has not been reported since they were stopped.
2136
2137 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002138
2139 .. versionadded:: 2.3
2140
2141The following functions take a process status code as returned by
2142:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
2143used to determine the disposition of a process.
2144
2145
2146.. function:: WCOREDUMP(status)
2147
Georg Brandlf725b952008-01-05 19:44:22 +00002148 Return ``True`` if a core dump was generated for the process, otherwise
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002149 return ``False``.
2150
2151 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002152
2153 .. versionadded:: 2.3
2154
2155
2156.. function:: WIFCONTINUED(status)
2157
Georg Brandlf725b952008-01-05 19:44:22 +00002158 Return ``True`` if the process has been continued from a job control stop,
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002159 otherwise return ``False``.
2160
2161 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002162
2163 .. versionadded:: 2.3
2164
2165
2166.. function:: WIFSTOPPED(status)
2167
Georg Brandlf725b952008-01-05 19:44:22 +00002168 Return ``True`` if the process has been stopped, otherwise return
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002169 ``False``.
2170
2171 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002172
2173
2174.. function:: WIFSIGNALED(status)
2175
Georg Brandlf725b952008-01-05 19:44:22 +00002176 Return ``True`` if the process exited due to a signal, otherwise return
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002177 ``False``.
2178
2179 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002180
2181
2182.. function:: WIFEXITED(status)
2183
Georg Brandlf725b952008-01-05 19:44:22 +00002184 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002185 otherwise return ``False``.
2186
2187 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002188
2189
2190.. function:: WEXITSTATUS(status)
2191
2192 If ``WIFEXITED(status)`` is true, return the integer parameter to the
2193 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002194
Georg Brandl9af94982008-09-13 17:41:16 +00002195 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002196
2197
2198.. function:: WSTOPSIG(status)
2199
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002200 Return the signal which caused the process to stop.
2201
2202 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002203
2204
2205.. function:: WTERMSIG(status)
2206
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002207 Return the signal which caused the process to exit.
2208
2209 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002210
2211
2212.. _os-path:
2213
2214Miscellaneous System Information
2215--------------------------------
2216
2217
2218.. function:: confstr(name)
2219
2220 Return string-valued system configuration values. *name* specifies the
2221 configuration value to retrieve; it may be a string which is the name of a
2222 defined system value; these names are specified in a number of standards (POSIX,
2223 Unix 95, Unix 98, and others). Some platforms define additional names as well.
2224 The names known to the host operating system are given as the keys of the
2225 ``confstr_names`` dictionary. For configuration variables not included in that
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002226 mapping, passing an integer for *name* is also accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002227
2228 If the configuration value specified by *name* isn't defined, ``None`` is
2229 returned.
2230
2231 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2232 specific value for *name* is not supported by the host system, even if it is
2233 included in ``confstr_names``, an :exc:`OSError` is raised with
2234 :const:`errno.EINVAL` for the error number.
2235
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002236 Availability: Unix
2237
Georg Brandl8ec7f652007-08-15 14:28:01 +00002238
2239.. data:: confstr_names
2240
2241 Dictionary mapping names accepted by :func:`confstr` to the integer values
2242 defined for those names by the host operating system. This can be used to
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002243 determine the set of names known to the system.
2244
2245 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002246
2247
2248.. function:: getloadavg()
2249
Georg Brandl57fe0f22008-01-12 10:53:29 +00002250 Return the number of processes in the system run queue averaged over the last
2251 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002252 unobtainable.
2253
2254 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002255
2256 .. versionadded:: 2.3
2257
2258
2259.. function:: sysconf(name)
2260
2261 Return integer-valued system configuration values. If the configuration value
2262 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2263 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2264 provides information on the known names is given by ``sysconf_names``.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002265
Georg Brandl9af94982008-09-13 17:41:16 +00002266 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002267
2268
2269.. data:: sysconf_names
2270
2271 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2272 defined for those names by the host operating system. This can be used to
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002273 determine the set of names known to the system.
2274
2275 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002276
Georg Brandlf725b952008-01-05 19:44:22 +00002277The following data values are used to support path manipulation operations. These
Georg Brandl8ec7f652007-08-15 14:28:01 +00002278are defined for all platforms.
2279
2280Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2281
2282
2283.. data:: curdir
2284
2285 The constant string used by the operating system to refer to the current
Georg Brandl9af94982008-09-13 17:41:16 +00002286 directory. This is ``'.'`` for Windows and POSIX. Also available via
2287 :mod:`os.path`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002288
2289
2290.. data:: pardir
2291
2292 The constant string used by the operating system to refer to the parent
Georg Brandl9af94982008-09-13 17:41:16 +00002293 directory. This is ``'..'`` for Windows and POSIX. Also available via
2294 :mod:`os.path`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002295
2296
2297.. data:: sep
2298
Georg Brandl9af94982008-09-13 17:41:16 +00002299 The character used by the operating system to separate pathname components.
2300 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
2301 is not sufficient to be able to parse or concatenate pathnames --- use
Georg Brandl8ec7f652007-08-15 14:28:01 +00002302 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2303 useful. Also available via :mod:`os.path`.
2304
2305
2306.. data:: altsep
2307
2308 An alternative character used by the operating system to separate pathname
2309 components, or ``None`` if only one separator character exists. This is set to
2310 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2311 :mod:`os.path`.
2312
2313
2314.. data:: extsep
2315
2316 The character which separates the base filename from the extension; for example,
2317 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2318
2319 .. versionadded:: 2.2
2320
2321
2322.. data:: pathsep
2323
2324 The character conventionally used by the operating system to separate search
2325 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2326 Windows. Also available via :mod:`os.path`.
2327
2328
2329.. data:: defpath
2330
2331 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
2332 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
2333
2334
2335.. data:: linesep
2336
2337 The string used to separate (or, rather, terminate) lines on the current
Georg Brandl9af94982008-09-13 17:41:16 +00002338 platform. This may be a single character, such as ``'\n'`` for POSIX, or
2339 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
2340 *os.linesep* as a line terminator when writing files opened in text mode (the
2341 default); use a single ``'\n'`` instead, on all platforms.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002342
2343
2344.. data:: devnull
2345
Georg Brandl9af94982008-09-13 17:41:16 +00002346 The file path of the null device. For example: ``'/dev/null'`` for POSIX.
2347 Also available via :mod:`os.path`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002348
2349 .. versionadded:: 2.4
2350
2351
2352.. _os-miscfunc:
2353
2354Miscellaneous Functions
2355-----------------------
2356
2357
2358.. function:: urandom(n)
2359
2360 Return a string of *n* random bytes suitable for cryptographic use.
2361
2362 This function returns random bytes from an OS-specific randomness source. The
2363 returned data should be unpredictable enough for cryptographic applications,
2364 though its exact quality depends on the OS implementation. On a UNIX-like
2365 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
2366 If a randomness source is not found, :exc:`NotImplementedError` will be raised.
2367
2368 .. versionadded:: 2.4
2369