blob: eb9cb193bcb3a09df374fd234fc878afa05e05d2 [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
Georg Brandleb412142010-05-18 23:19:34 +0000680.. data:: SEEK_SET
681 SEEK_CUR
682 SEEK_END
683
684 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
685 respectively. Availability: Windows, Unix.
686
687 .. versionadded:: 2.5
688
689
Georg Brandl8ec7f652007-08-15 14:28:01 +0000690.. function:: open(file, flags[, mode])
691
692 Open the file *file* and set various flags according to *flags* and possibly its
693 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
694 current umask value is first masked out. Return the file descriptor for the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000695 newly opened file.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000696
697 For a description of the flag and mode values, see the C run-time documentation;
698 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
Georg Brandleb412142010-05-18 23:19:34 +0000699 this module too (see :ref:`open-constants`). In particular, on Windows adding
700 :const:`O_BINARY` is needed to open files in binary mode.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000701
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000702 Availability: Unix, Windows.
703
Georg Brandl8ec7f652007-08-15 14:28:01 +0000704 .. note::
705
Georg Brandl0dfdf002009-10-27 14:36:50 +0000706 This function is intended for low-level I/O. For normal usage, use the
707 built-in function :func:`open`, which returns a "file object" with
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000708 :meth:`~file.read` and :meth:`~file.wprite` methods (and many more). To
Georg Brandl0dfdf002009-10-27 14:36:50 +0000709 wrap a file descriptor in a "file object", use :func:`fdopen`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000710
711
712.. function:: openpty()
713
714 .. index:: module: pty
715
716 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
717 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000718 approach, use the :mod:`pty` module.
719
720 Availability: some flavors of Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000721
722
723.. function:: pipe()
724
725 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000726 and writing, respectively.
727
728 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000729
730
731.. function:: read(fd, n)
732
733 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
734 bytes read. If the end of the file referred to by *fd* has been reached, an
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000735 empty string is returned.
736
737 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000738
739 .. note::
740
741 This function is intended for low-level I/O and must be applied to a file
Georg Brandle081eef2009-05-26 09:04:23 +0000742 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a "file object"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000743 returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandle081eef2009-05-26 09:04:23 +0000744 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
745 :meth:`~file.readline` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000746
747
748.. function:: tcgetpgrp(fd)
749
750 Return the process group associated with the terminal given by *fd* (an open
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000751 file descriptor as returned by :func:`os.open`).
752
753 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000754
755
756.. function:: tcsetpgrp(fd, pg)
757
758 Set the process group associated with the terminal given by *fd* (an open file
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000759 descriptor as returned by :func:`os.open`) to *pg*.
760
761 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000762
763
764.. function:: ttyname(fd)
765
766 Return a string which specifies the terminal device associated with
Georg Brandlbb75e4e2007-10-21 10:46:24 +0000767 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000768 exception is raised.
769
770 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000771
772
773.. function:: write(fd, str)
774
775 Write the string *str* to file descriptor *fd*. Return the number of bytes
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000776 actually written.
777
778 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000779
780 .. note::
781
782 This function is intended for low-level I/O and must be applied to a file
Georg Brandle081eef2009-05-26 09:04:23 +0000783 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
Georg Brandl8ec7f652007-08-15 14:28:01 +0000784 object" returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandle081eef2009-05-26 09:04:23 +0000785 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
786 :meth:`~file.write` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000787
Georg Brandleb412142010-05-18 23:19:34 +0000788
789.. _open-constants:
790
791``open()`` flag constants
792~~~~~~~~~~~~~~~~~~~~~~~~~
793
Georg Brandlfa71a902008-12-05 09:08:28 +0000794The following constants are options for the *flags* parameter to the
Georg Brandle081eef2009-05-26 09:04:23 +0000795:func:`~os.open` function. They can be combined using the bitwise OR operator
Georg Brandlfa71a902008-12-05 09:08:28 +0000796``|``. Some of them are not available on all platforms. For descriptions of
Georg Brandlf3a0b862008-12-07 14:47:12 +0000797their availability and use, consult the :manpage:`open(2)` manual page on Unix
Doug Hellmann0108ed32009-09-20 20:55:04 +0000798or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000799
800
801.. data:: O_RDONLY
802 O_WRONLY
803 O_RDWR
804 O_APPEND
805 O_CREAT
806 O_EXCL
807 O_TRUNC
808
Georg Brandlfa71a902008-12-05 09:08:28 +0000809 These constants are available on Unix and Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000810
811
812.. data:: O_DSYNC
813 O_RSYNC
814 O_SYNC
815 O_NDELAY
816 O_NONBLOCK
817 O_NOCTTY
818 O_SHLOCK
819 O_EXLOCK
820
Georg Brandlfa71a902008-12-05 09:08:28 +0000821 These constants are only available on Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000822
823
824.. data:: O_BINARY
Georg Brandlb67da6e2007-11-24 13:56:09 +0000825 O_NOINHERIT
Georg Brandl8ec7f652007-08-15 14:28:01 +0000826 O_SHORT_LIVED
827 O_TEMPORARY
828 O_RANDOM
829 O_SEQUENTIAL
830 O_TEXT
831
Georg Brandlfa71a902008-12-05 09:08:28 +0000832 These constants are only available on Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000833
834
Georg Brandlae6b9f32008-05-16 13:41:26 +0000835.. data:: O_ASYNC
836 O_DIRECT
Georg Brandlb67da6e2007-11-24 13:56:09 +0000837 O_DIRECTORY
838 O_NOFOLLOW
839 O_NOATIME
840
Georg Brandlfa71a902008-12-05 09:08:28 +0000841 These constants are GNU extensions and not present if they are not defined by
842 the C library.
Georg Brandlb67da6e2007-11-24 13:56:09 +0000843
844
Georg Brandl8ec7f652007-08-15 14:28:01 +0000845.. _os-file-dir:
846
847Files and Directories
848---------------------
849
Georg Brandl8ec7f652007-08-15 14:28:01 +0000850.. function:: access(path, mode)
851
852 Use the real uid/gid to test for access to *path*. Note that most operations
853 will use the effective uid/gid, therefore this routine can be used in a
854 suid/sgid environment to test if the invoking user has the specified access to
855 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
856 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
857 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
858 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000859 information.
860
861 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000862
863 .. note::
864
Georg Brandl0dfdf002009-10-27 14:36:50 +0000865 Using :func:`access` to check if a user is authorized to e.g. open a file
866 before actually doing so using :func:`open` creates a security hole,
867 because the user might exploit the short time interval between checking
868 and opening the file to manipulate it.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000869
870 .. note::
871
872 I/O operations may fail even when :func:`access` indicates that they would
873 succeed, particularly for operations on network filesystems which may have
874 permissions semantics beyond the usual POSIX permission-bit model.
875
876
877.. data:: F_OK
878
879 Value to pass as the *mode* parameter of :func:`access` to test the existence of
880 *path*.
881
882
883.. data:: R_OK
884
885 Value to include in the *mode* parameter of :func:`access` to test the
886 readability of *path*.
887
888
889.. data:: W_OK
890
891 Value to include in the *mode* parameter of :func:`access` to test the
892 writability of *path*.
893
894
895.. data:: X_OK
896
897 Value to include in the *mode* parameter of :func:`access` to determine if
898 *path* can be executed.
899
900
901.. function:: chdir(path)
902
903 .. index:: single: directory; changing
904
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000905 Change the current working directory to *path*.
906
907 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000908
909
910.. function:: fchdir(fd)
911
912 Change the current working directory to the directory represented by the file
913 descriptor *fd*. The descriptor must refer to an opened directory, not an open
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000914 file.
915
916 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000917
918 .. versionadded:: 2.3
919
920
921.. function:: getcwd()
922
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000923 Return a string representing the current working directory.
924
925 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000926
927
928.. function:: getcwdu()
929
930 Return a Unicode object representing the current working directory.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +0000931
Georg Brandl9af94982008-09-13 17:41:16 +0000932 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000933
934 .. versionadded:: 2.3
935
936
937.. function:: chflags(path, flags)
938
939 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
940 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
941
942 * ``UF_NODUMP``
943 * ``UF_IMMUTABLE``
944 * ``UF_APPEND``
945 * ``UF_OPAQUE``
946 * ``UF_NOUNLINK``
947 * ``SF_ARCHIVED``
948 * ``SF_IMMUTABLE``
949 * ``SF_APPEND``
950 * ``SF_NOUNLINK``
951 * ``SF_SNAPSHOT``
952
Georg Brandl9af94982008-09-13 17:41:16 +0000953 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000954
955 .. versionadded:: 2.6
956
957
958.. function:: chroot(path)
959
960 Change the root directory of the current process to *path*. Availability:
Georg Brandl9af94982008-09-13 17:41:16 +0000961 Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000962
963 .. versionadded:: 2.2
964
965
966.. function:: chmod(path, mode)
967
968 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Georg Brandlf725b952008-01-05 19:44:22 +0000969 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl8ec7f652007-08-15 14:28:01 +0000970 combinations of them:
971
972
R. David Murrayba2c2b12009-07-21 14:23:11 +0000973 * :data:`stat.S_ISUID`
974 * :data:`stat.S_ISGID`
975 * :data:`stat.S_ENFMT`
976 * :data:`stat.S_ISVTX`
977 * :data:`stat.S_IREAD`
978 * :data:`stat.S_IWRITE`
979 * :data:`stat.S_IEXEC`
980 * :data:`stat.S_IRWXU`
981 * :data:`stat.S_IRUSR`
982 * :data:`stat.S_IWUSR`
983 * :data:`stat.S_IXUSR`
984 * :data:`stat.S_IRWXG`
985 * :data:`stat.S_IRGRP`
986 * :data:`stat.S_IWGRP`
987 * :data:`stat.S_IXGRP`
988 * :data:`stat.S_IRWXO`
989 * :data:`stat.S_IROTH`
990 * :data:`stat.S_IWOTH`
991 * :data:`stat.S_IXOTH`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000992
Georg Brandl9af94982008-09-13 17:41:16 +0000993 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000994
995 .. note::
996
997 Although Windows supports :func:`chmod`, you can only set the file's read-only
998 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
999 constants or a corresponding integer value). All other bits are
1000 ignored.
1001
1002
1003.. function:: chown(path, uid, gid)
1004
1005 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001006 one of the ids unchanged, set it to -1.
1007
1008 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001009
1010
1011.. function:: lchflags(path, flags)
1012
1013 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001014 follow symbolic links.
1015
1016 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001017
1018 .. versionadded:: 2.6
1019
1020
Georg Brandl81ddc1a2007-11-30 22:04:45 +00001021.. function:: lchmod(path, mode)
1022
1023 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
1024 affects the symlink rather than the target. See the docs for :func:`chmod`
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001025 for possible values of *mode*.
1026
1027 Availability: Unix.
Georg Brandl81ddc1a2007-11-30 22:04:45 +00001028
1029 .. versionadded:: 2.6
1030
1031
Georg Brandl8ec7f652007-08-15 14:28:01 +00001032.. function:: lchown(path, uid, gid)
1033
Georg Brandlf725b952008-01-05 19:44:22 +00001034 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001035 function will not follow symbolic links.
1036
1037 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001038
1039 .. versionadded:: 2.3
1040
1041
Georg Brandl78559542009-10-27 14:03:07 +00001042.. function:: link(source, link_name)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001043
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001044 Create a hard link pointing to *source* named *link_name*.
1045
1046 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001047
1048
1049.. function:: listdir(path)
1050
Georg Brandld2094602008-12-05 08:51:30 +00001051 Return a list containing the names of the entries in the directory given by
1052 *path*. The list is in arbitrary order. It does not include the special
1053 entries ``'.'`` and ``'..'`` even if they are present in the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001054 directory.
1055
1056 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001057
1058 .. versionchanged:: 2.3
1059 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
Georg Brandle081eef2009-05-26 09:04:23 +00001060 a list of Unicode objects. Undecodable filenames will still be returned as
1061 string objects.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001062
1063
1064.. function:: lstat(path)
1065
Georg Brandl03b15c62007-11-01 17:19:33 +00001066 Like :func:`stat`, but do not follow symbolic links. This is an alias for
1067 :func:`stat` on platforms that do not support symbolic links, such as
1068 Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001069
1070
1071.. function:: mkfifo(path[, mode])
1072
1073 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
1074 *mode* is ``0666`` (octal). The current umask value is first masked out from
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001075 the mode.
1076
1077 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001078
1079 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
1080 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
1081 rendezvous between "client" and "server" type processes: the server opens the
1082 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
1083 doesn't open the FIFO --- it just creates the rendezvous point.
1084
1085
1086.. function:: mknod(filename[, mode=0600, device])
1087
1088 Create a filesystem node (file, device special file or named pipe) named
1089 *filename*. *mode* specifies both the permissions to use and the type of node to
1090 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
1091 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
1092 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
1093 For ``stat.S_IFCHR`` and
1094 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
1095 :func:`os.makedev`), otherwise it is ignored.
1096
1097 .. versionadded:: 2.3
1098
1099
1100.. function:: major(device)
1101
Georg Brandlf725b952008-01-05 19:44:22 +00001102 Extract the device major number from a raw device number (usually the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001103 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
1104
1105 .. versionadded:: 2.3
1106
1107
1108.. function:: minor(device)
1109
Georg Brandlf725b952008-01-05 19:44:22 +00001110 Extract the device minor number from a raw device number (usually the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001111 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
1112
1113 .. versionadded:: 2.3
1114
1115
1116.. function:: makedev(major, minor)
1117
Georg Brandlf725b952008-01-05 19:44:22 +00001118 Compose a raw device number from the major and minor device numbers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001119
1120 .. versionadded:: 2.3
1121
1122
1123.. function:: mkdir(path[, mode])
1124
1125 Create a directory named *path* with numeric mode *mode*. The default *mode* is
1126 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001127 current umask value is first masked out.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001128
Mark Summerfieldac3d4292007-11-02 08:24:59 +00001129 It is also possible to create temporary directories; see the
1130 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1131
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001132 Availability: Unix, Windows.
1133
Georg Brandl8ec7f652007-08-15 14:28:01 +00001134
1135.. function:: makedirs(path[, mode])
1136
1137 .. index::
1138 single: directory; creating
1139 single: UNC paths; and os.makedirs()
1140
1141 Recursive directory creation function. Like :func:`mkdir`, but makes all
1142 intermediate-level directories needed to contain the leaf directory. Throws an
1143 :exc:`error` exception if the leaf directory already exists or cannot be
1144 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
1145 ignored. Where it is used, the current umask value is first masked out.
1146
1147 .. note::
1148
1149 :func:`makedirs` will become confused if the path elements to create include
Georg Brandlf725b952008-01-05 19:44:22 +00001150 :data:`os.pardir`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001151
1152 .. versionadded:: 1.5.2
1153
1154 .. versionchanged:: 2.3
1155 This function now handles UNC paths correctly.
1156
1157
1158.. function:: pathconf(path, name)
1159
1160 Return system configuration information relevant to a named file. *name*
1161 specifies the configuration value to retrieve; it may be a string which is the
1162 name of a defined system value; these names are specified in a number of
1163 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1164 additional names as well. The names known to the host operating system are
1165 given in the ``pathconf_names`` dictionary. For configuration variables not
1166 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001167
1168 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1169 specific value for *name* is not supported by the host system, even if it is
1170 included in ``pathconf_names``, an :exc:`OSError` is raised with
1171 :const:`errno.EINVAL` for the error number.
1172
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001173 Availability: Unix.
1174
Georg Brandl8ec7f652007-08-15 14:28:01 +00001175
1176.. data:: pathconf_names
1177
1178 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1179 the integer values defined for those names by the host operating system. This
1180 can be used to determine the set of names known to the system. Availability:
Georg Brandl9af94982008-09-13 17:41:16 +00001181 Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001182
1183
1184.. function:: readlink(path)
1185
1186 Return a string representing the path to which the symbolic link points. The
1187 result may be either an absolute or relative pathname; if it is relative, it may
1188 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1189 result)``.
1190
1191 .. versionchanged:: 2.6
1192 If the *path* is a Unicode object the result will also be a Unicode object.
1193
Georg Brandl9af94982008-09-13 17:41:16 +00001194 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001195
1196
1197.. function:: remove(path)
1198
Georg Brandl5be70d42009-10-27 14:50:20 +00001199 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
1200 raised; see :func:`rmdir` below to remove a directory. This is identical to
1201 the :func:`unlink` function documented below. On Windows, attempting to
1202 remove a file that is in use causes an exception to be raised; on Unix, the
1203 directory entry is removed but the storage allocated to the file is not made
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001204 available until the original file is no longer in use.
1205
1206 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001207
1208
1209.. function:: removedirs(path)
1210
1211 .. index:: single: directory; deleting
1212
Georg Brandlf725b952008-01-05 19:44:22 +00001213 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001214 leaf directory is successfully removed, :func:`removedirs` tries to
1215 successively remove every parent directory mentioned in *path* until an error
1216 is raised (which is ignored, because it generally means that a parent directory
1217 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1218 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1219 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1220 successfully removed.
1221
1222 .. versionadded:: 1.5.2
1223
1224
1225.. function:: rename(src, dst)
1226
1227 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1228 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Georg Brandlf725b952008-01-05 19:44:22 +00001229 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl8ec7f652007-08-15 14:28:01 +00001230 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1231 the renaming will be an atomic operation (this is a POSIX requirement). On
1232 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1233 file; there may be no way to implement an atomic rename when *dst* names an
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001234 existing file.
1235
1236 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001237
1238
1239.. function:: renames(old, new)
1240
1241 Recursive directory or file renaming function. Works like :func:`rename`, except
1242 creation of any intermediate directories needed to make the new pathname good is
1243 attempted first. After the rename, directories corresponding to rightmost path
1244 segments of the old name will be pruned away using :func:`removedirs`.
1245
1246 .. versionadded:: 1.5.2
1247
1248 .. note::
1249
1250 This function can fail with the new directory structure made if you lack
1251 permissions needed to remove the leaf directory or file.
1252
1253
1254.. function:: rmdir(path)
1255
Georg Brandl5be70d42009-10-27 14:50:20 +00001256 Remove (delete) the directory *path*. Only works when the directory is
1257 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001258 directory trees, :func:`shutil.rmtree` can be used.
1259
1260 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001261
1262
1263.. function:: stat(path)
1264
1265 Perform a :cfunc:`stat` system call on the given path. The return value is an
1266 object whose attributes correspond to the members of the :ctype:`stat`
1267 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1268 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
Georg Brandlf725b952008-01-05 19:44:22 +00001269 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
Georg Brandl8ec7f652007-08-15 14:28:01 +00001270 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1271 access), :attr:`st_mtime` (time of most recent content modification),
1272 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1273 Unix, or the time of creation on Windows)::
1274
1275 >>> import os
1276 >>> statinfo = os.stat('somefile.txt')
1277 >>> statinfo
1278 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1279 >>> statinfo.st_size
1280 926L
1281 >>>
1282
1283 .. versionchanged:: 2.3
Georg Brandlf725b952008-01-05 19:44:22 +00001284 If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
Georg Brandl8ec7f652007-08-15 14:28:01 +00001285 seconds. Fractions of a second may be reported if the system supports that. On
1286 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1287 discussion.
1288
1289 On some Unix systems (such as Linux), the following attributes may also be
1290 available: :attr:`st_blocks` (number of blocks allocated for file),
1291 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1292 inode device). :attr:`st_flags` (user defined flags for file).
1293
1294 On other Unix systems (such as FreeBSD), the following attributes may be
1295 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1296 (file generation number), :attr:`st_birthtime` (time of file creation).
1297
1298 On Mac OS systems, the following attributes may also be available:
1299 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1300
1301 On RISCOS systems, the following attributes are also available: :attr:`st_ftype`
1302 (file type), :attr:`st_attrs` (attributes), :attr:`st_obtype` (object type).
1303
1304 .. index:: module: stat
1305
1306 For backward compatibility, the return value of :func:`stat` is also accessible
1307 as a tuple of at least 10 integers giving the most important (and portable)
1308 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1309 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1310 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1311 :attr:`st_ctime`. More items may be added at the end by some implementations.
1312 The standard module :mod:`stat` defines functions and constants that are useful
1313 for extracting information from a :ctype:`stat` structure. (On Windows, some
1314 items are filled with dummy values.)
1315
1316 .. note::
1317
1318 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1319 :attr:`st_ctime` members depends on the operating system and the file system.
1320 For example, on Windows systems using the FAT or FAT32 file systems,
1321 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1322 resolution. See your operating system documentation for details.
1323
Georg Brandl9af94982008-09-13 17:41:16 +00001324 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001325
1326 .. versionchanged:: 2.2
1327 Added access to values as attributes of the returned object.
1328
1329 .. versionchanged:: 2.5
Georg Brandlf725b952008-01-05 19:44:22 +00001330 Added :attr:`st_gen` and :attr:`st_birthtime`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001331
1332
1333.. function:: stat_float_times([newvalue])
1334
1335 Determine whether :class:`stat_result` represents time stamps as float objects.
1336 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1337 ``False``, future calls return ints. If *newvalue* is omitted, return the
1338 current setting.
1339
1340 For compatibility with older Python versions, accessing :class:`stat_result` as
1341 a tuple always returns integers.
1342
1343 .. versionchanged:: 2.5
1344 Python now returns float values by default. Applications which do not work
1345 correctly with floating point time stamps can use this function to restore the
1346 old behaviour.
1347
1348 The resolution of the timestamps (that is the smallest possible fraction)
1349 depends on the system. Some systems only support second resolution; on these
1350 systems, the fraction will always be zero.
1351
1352 It is recommended that this setting is only changed at program startup time in
1353 the *__main__* module; libraries should never change this setting. If an
1354 application uses a library that works incorrectly if floating point time stamps
1355 are processed, this application should turn the feature off until the library
1356 has been corrected.
1357
1358
1359.. function:: statvfs(path)
1360
1361 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1362 an object whose attributes describe the filesystem on the given path, and
1363 correspond to the members of the :ctype:`statvfs` structure, namely:
1364 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1365 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001366 :attr:`f_flag`, :attr:`f_namemax`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001367
1368 .. index:: module: statvfs
1369
1370 For backward compatibility, the return value is also accessible as a tuple whose
1371 values correspond to the attributes, in the order given above. The standard
1372 module :mod:`statvfs` defines constants that are useful for extracting
1373 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1374 this remains useful when writing code that needs to work with versions of Python
1375 that don't support accessing the fields as attributes.
1376
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001377 Availability: Unix.
1378
Georg Brandl8ec7f652007-08-15 14:28:01 +00001379 .. versionchanged:: 2.2
1380 Added access to values as attributes of the returned object.
1381
1382
Georg Brandl78559542009-10-27 14:03:07 +00001383.. function:: symlink(source, link_name)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001384
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001385 Create a symbolic link pointing to *source* named *link_name*.
1386
1387 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001388
1389
1390.. function:: tempnam([dir[, prefix]])
1391
1392 Return a unique path name that is reasonable for creating a temporary file.
1393 This will be an absolute path that names a potential directory entry in the
1394 directory *dir* or a common location for temporary files if *dir* is omitted or
1395 ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
1396 to the filename. Applications are responsible for properly creating and
1397 managing files created using paths returned by :func:`tempnam`; no automatic
1398 cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
Georg Brandlf725b952008-01-05 19:44:22 +00001399 overrides *dir*, while on Windows :envvar:`TMP` is used. The specific
Georg Brandl8ec7f652007-08-15 14:28:01 +00001400 behavior of this function depends on the C library implementation; some aspects
1401 are underspecified in system documentation.
1402
1403 .. warning::
1404
1405 Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1406 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1407
Georg Brandl9af94982008-09-13 17:41:16 +00001408 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001409
1410
1411.. function:: tmpnam()
1412
1413 Return a unique path name that is reasonable for creating a temporary file.
1414 This will be an absolute path that names a potential directory entry in a common
1415 location for temporary files. Applications are responsible for properly
1416 creating and managing files created using paths returned by :func:`tmpnam`; no
1417 automatic cleanup is provided.
1418
1419 .. warning::
1420
1421 Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1422 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1423
1424 Availability: Unix, Windows. This function probably shouldn't be used on
1425 Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1426 name in the root directory of the current drive, and that's generally a poor
1427 location for a temp file (depending on privileges, you may not even be able to
1428 open a file using this name).
1429
1430
1431.. data:: TMP_MAX
1432
1433 The maximum number of unique names that :func:`tmpnam` will generate before
1434 reusing names.
1435
1436
1437.. function:: unlink(path)
1438
Georg Brandl5be70d42009-10-27 14:50:20 +00001439 Remove (delete) the file *path*. This is the same function as
1440 :func:`remove`; the :func:`unlink` name is its traditional Unix
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001441 name.
1442
1443 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001444
1445
1446.. function:: utime(path, times)
1447
Benjamin Peterson5b02ef32008-08-16 03:13:07 +00001448 Set the access and modified times of the file specified by *path*. If *times*
1449 is ``None``, then the file's access and modified times are set to the current
1450 time. (The effect is similar to running the Unix program :program:`touch` on
1451 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1452 ``(atime, mtime)`` which is used to set the access and modified times,
1453 respectively. Whether a directory can be given for *path* depends on whether
1454 the operating system implements directories as files (for example, Windows
1455 does not). Note that the exact times you set here may not be returned by a
1456 subsequent :func:`stat` call, depending on the resolution with which your
1457 operating system records access and modification times; see :func:`stat`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001458
1459 .. versionchanged:: 2.0
1460 Added support for ``None`` for *times*.
1461
Georg Brandl9af94982008-09-13 17:41:16 +00001462 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001463
1464
1465.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1466
1467 .. index::
1468 single: directory; walking
1469 single: directory; traversal
1470
Georg Brandlf725b952008-01-05 19:44:22 +00001471 Generate the file names in a directory tree by walking the tree
1472 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl8ec7f652007-08-15 14:28:01 +00001473 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1474 filenames)``.
1475
1476 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1477 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1478 *filenames* is a list of the names of the non-directory files in *dirpath*.
1479 Note that the names in the lists contain no path components. To get a full path
1480 (which begins with *top*) to a file or directory in *dirpath*, do
1481 ``os.path.join(dirpath, name)``.
1482
Georg Brandlf725b952008-01-05 19:44:22 +00001483 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001484 directory is generated before the triples for any of its subdirectories
Georg Brandlf725b952008-01-05 19:44:22 +00001485 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001486 directory is generated after the triples for all of its subdirectories
Georg Brandlf725b952008-01-05 19:44:22 +00001487 (directories are generated bottom-up).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001488
Georg Brandlf725b952008-01-05 19:44:22 +00001489 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl8ec7f652007-08-15 14:28:01 +00001490 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1491 recurse into the subdirectories whose names remain in *dirnames*; this can be
1492 used to prune the search, impose a specific order of visiting, or even to inform
1493 :func:`walk` about directories the caller creates or renames before it resumes
Georg Brandlf725b952008-01-05 19:44:22 +00001494 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001495 ineffective, because in bottom-up mode the directories in *dirnames* are
1496 generated before *dirpath* itself is generated.
1497
Georg Brandlf725b952008-01-05 19:44:22 +00001498 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl8ec7f652007-08-15 14:28:01 +00001499 argument *onerror* is specified, it should be a function; it will be called with
1500 one argument, an :exc:`OSError` instance. It can report the error to continue
1501 with the walk, or raise the exception to abort the walk. Note that the filename
1502 is available as the ``filename`` attribute of the exception object.
1503
1504 By default, :func:`walk` will not walk down into symbolic links that resolve to
Georg Brandlf725b952008-01-05 19:44:22 +00001505 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl8ec7f652007-08-15 14:28:01 +00001506 symlinks, on systems that support them.
1507
1508 .. versionadded:: 2.6
1509 The *followlinks* parameter.
1510
1511 .. note::
1512
Georg Brandlf725b952008-01-05 19:44:22 +00001513 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001514 link points to a parent directory of itself. :func:`walk` does not keep track of
1515 the directories it visited already.
1516
1517 .. note::
1518
1519 If you pass a relative pathname, don't change the current working directory
1520 between resumptions of :func:`walk`. :func:`walk` never changes the current
1521 directory, and assumes that its caller doesn't either.
1522
1523 This example displays the number of bytes taken by non-directory files in each
1524 directory under the starting directory, except that it doesn't look under any
1525 CVS subdirectory::
1526
1527 import os
1528 from os.path import join, getsize
1529 for root, dirs, files in os.walk('python/Lib/email'):
1530 print root, "consumes",
1531 print sum(getsize(join(root, name)) for name in files),
1532 print "bytes in", len(files), "non-directory files"
1533 if 'CVS' in dirs:
1534 dirs.remove('CVS') # don't visit CVS directories
1535
Georg Brandlf725b952008-01-05 19:44:22 +00001536 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001537 doesn't allow deleting a directory before the directory is empty::
1538
Georg Brandlf725b952008-01-05 19:44:22 +00001539 # Delete everything reachable from the directory named in "top",
Georg Brandl8ec7f652007-08-15 14:28:01 +00001540 # assuming there are no symbolic links.
1541 # CAUTION: This is dangerous! For example, if top == '/', it
1542 # could delete all your disk files.
1543 import os
1544 for root, dirs, files in os.walk(top, topdown=False):
1545 for name in files:
1546 os.remove(os.path.join(root, name))
1547 for name in dirs:
1548 os.rmdir(os.path.join(root, name))
1549
1550 .. versionadded:: 2.3
1551
1552
1553.. _os-process:
1554
1555Process Management
1556------------------
1557
1558These functions may be used to create and manage processes.
1559
1560The various :func:`exec\*` functions take a list of arguments for the new
1561program loaded into the process. In each case, the first of these arguments is
1562passed to the new program as its own name rather than as an argument a user may
1563have typed on a command line. For the C programmer, this is the ``argv[0]``
1564passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1565['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1566to be ignored.
1567
1568
1569.. function:: abort()
1570
1571 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1572 behavior is to produce a core dump; on Windows, the process immediately returns
1573 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1574 to register a handler for :const:`SIGABRT` will behave differently.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001575
Georg Brandl9af94982008-09-13 17:41:16 +00001576 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001577
1578
1579.. function:: execl(path, arg0, arg1, ...)
1580 execle(path, arg0, arg1, ..., env)
1581 execlp(file, arg0, arg1, ...)
1582 execlpe(file, arg0, arg1, ..., env)
1583 execv(path, args)
1584 execve(path, args, env)
1585 execvp(file, args)
1586 execvpe(file, args, env)
1587
1588 These functions all execute a new program, replacing the current process; they
1589 do not return. On Unix, the new executable is loaded into the current process,
Georg Brandlf725b952008-01-05 19:44:22 +00001590 and will have the same process id as the caller. Errors will be reported as
Georg Brandl734373c2009-01-03 21:55:17 +00001591 :exc:`OSError` exceptions.
Andrew M. Kuchlingac771662008-09-28 00:15:27 +00001592
1593 The current process is replaced immediately. Open file objects and
1594 descriptors are not flushed, so if there may be data buffered
1595 on these open files, you should flush them using
1596 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
1597 :func:`exec\*` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001598
Georg Brandlf725b952008-01-05 19:44:22 +00001599 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1600 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl8ec7f652007-08-15 14:28:01 +00001601 to work with if the number of parameters is fixed when the code is written; the
1602 individual parameters simply become additional parameters to the :func:`execl\*`
Georg Brandlf725b952008-01-05 19:44:22 +00001603 functions. The "v" variants are good when the number of parameters is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001604 variable, with the arguments being passed in a list or tuple as the *args*
1605 parameter. In either case, the arguments to the child process should start with
1606 the name of the command being run, but this is not enforced.
1607
Georg Brandlf725b952008-01-05 19:44:22 +00001608 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001609 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1610 :envvar:`PATH` environment variable to locate the program *file*. When the
1611 environment is being replaced (using one of the :func:`exec\*e` variants,
1612 discussed in the next paragraph), the new environment is used as the source of
1613 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1614 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1615 locate the executable; *path* must contain an appropriate absolute or relative
1616 path.
1617
1618 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Georg Brandlf725b952008-01-05 19:44:22 +00001619 that these all end in "e"), the *env* parameter must be a mapping which is
Georg Brandlfb246c42008-04-19 16:58:28 +00001620 used to define the environment variables for the new process (these are used
1621 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001622 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
Georg Brandl734373c2009-01-03 21:55:17 +00001623 inherit the environment of the current process.
Andrew M. Kuchlingac771662008-09-28 00:15:27 +00001624
1625 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001626
1627
1628.. function:: _exit(n)
1629
1630 Exit to the system with status *n*, without calling cleanup handlers, flushing
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001631 stdio buffers, etc.
1632
1633 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001634
1635 .. note::
1636
1637 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1638 be used in the child process after a :func:`fork`.
1639
Georg Brandlf725b952008-01-05 19:44:22 +00001640The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001641although they are not required. These are typically used for system programs
1642written in Python, such as a mail server's external command delivery program.
1643
1644.. note::
1645
1646 Some of these may not be available on all Unix platforms, since there is some
1647 variation. These constants are defined where they are defined by the underlying
1648 platform.
1649
1650
1651.. data:: EX_OK
1652
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001653 Exit code that means no error occurred.
1654
1655 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001656
1657 .. versionadded:: 2.3
1658
1659
1660.. data:: EX_USAGE
1661
1662 Exit code that means the command was used incorrectly, such as when the wrong
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001663 number of arguments are given.
1664
1665 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001666
1667 .. versionadded:: 2.3
1668
1669
1670.. data:: EX_DATAERR
1671
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001672 Exit code that means the input data was incorrect.
1673
1674 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001675
1676 .. versionadded:: 2.3
1677
1678
1679.. data:: EX_NOINPUT
1680
1681 Exit code that means an input file did not exist or was not readable.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001682
Georg Brandl9af94982008-09-13 17:41:16 +00001683 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001684
1685 .. versionadded:: 2.3
1686
1687
1688.. data:: EX_NOUSER
1689
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001690 Exit code that means a specified user did not exist.
1691
1692 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001693
1694 .. versionadded:: 2.3
1695
1696
1697.. data:: EX_NOHOST
1698
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001699 Exit code that means a specified host did not exist.
1700
1701 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001702
1703 .. versionadded:: 2.3
1704
1705
1706.. data:: EX_UNAVAILABLE
1707
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001708 Exit code that means that a required service is unavailable.
1709
1710 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001711
1712 .. versionadded:: 2.3
1713
1714
1715.. data:: EX_SOFTWARE
1716
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001717 Exit code that means an internal software error was detected.
1718
1719 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001720
1721 .. versionadded:: 2.3
1722
1723
1724.. data:: EX_OSERR
1725
1726 Exit code that means an operating system error was detected, such as the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001727 inability to fork or create a pipe.
1728
1729 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001730
1731 .. versionadded:: 2.3
1732
1733
1734.. data:: EX_OSFILE
1735
1736 Exit code that means some system file did not exist, could not be opened, or had
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001737 some other kind of error.
1738
1739 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001740
1741 .. versionadded:: 2.3
1742
1743
1744.. data:: EX_CANTCREAT
1745
1746 Exit code that means a user specified output file could not be created.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001747
Georg Brandl9af94982008-09-13 17:41:16 +00001748 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001749
1750 .. versionadded:: 2.3
1751
1752
1753.. data:: EX_IOERR
1754
1755 Exit code that means that an error occurred while doing I/O on some file.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001756
Georg Brandl9af94982008-09-13 17:41:16 +00001757 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001758
1759 .. versionadded:: 2.3
1760
1761
1762.. data:: EX_TEMPFAIL
1763
1764 Exit code that means a temporary failure occurred. This indicates something
1765 that may not really be an error, such as a network connection that couldn't be
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001766 made during a retryable operation.
1767
1768 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001769
1770 .. versionadded:: 2.3
1771
1772
1773.. data:: EX_PROTOCOL
1774
1775 Exit code that means that a protocol exchange was illegal, invalid, or not
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001776 understood.
1777
1778 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001779
1780 .. versionadded:: 2.3
1781
1782
1783.. data:: EX_NOPERM
1784
1785 Exit code that means that there were insufficient permissions to perform the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001786 operation (but not intended for file system problems).
1787
1788 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001789
1790 .. versionadded:: 2.3
1791
1792
1793.. data:: EX_CONFIG
1794
1795 Exit code that means that some kind of configuration error occurred.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001796
Georg Brandl9af94982008-09-13 17:41:16 +00001797 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001798
1799 .. versionadded:: 2.3
1800
1801
1802.. data:: EX_NOTFOUND
1803
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001804 Exit code that means something like "an entry was not found".
1805
1806 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001807
1808 .. versionadded:: 2.3
1809
1810
1811.. function:: fork()
1812
Georg Brandlf725b952008-01-05 19:44:22 +00001813 Fork a child process. Return ``0`` in the child and the child's process id in the
Skip Montanaro75e51682008-03-15 02:32:49 +00001814 parent. If an error occurs :exc:`OSError` is raised.
Gregory P. Smith08067492008-09-30 20:41:13 +00001815
1816 Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
1817 known issues when using fork() from a thread.
1818
Georg Brandl9af94982008-09-13 17:41:16 +00001819 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001820
1821
1822.. function:: forkpty()
1823
1824 Fork a child process, using a new pseudo-terminal as the child's controlling
1825 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1826 new child's process id in the parent, and *fd* is the file descriptor of the
1827 master end of the pseudo-terminal. For a more portable approach, use the
Skip Montanaro75e51682008-03-15 02:32:49 +00001828 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001829
Georg Brandl9af94982008-09-13 17:41:16 +00001830 Availability: some flavors of Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001831
1832
1833.. function:: kill(pid, sig)
1834
1835 .. index::
1836 single: process; killing
1837 single: process; signalling
1838
1839 Send signal *sig* to the process *pid*. Constants for the specific signals
1840 available on the host platform are defined in the :mod:`signal` module.
Georg Brandl9af94982008-09-13 17:41:16 +00001841 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001842
1843
1844.. function:: killpg(pgid, sig)
1845
1846 .. index::
1847 single: process; killing
1848 single: process; signalling
1849
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001850 Send the signal *sig* to the process group *pgid*.
1851
1852 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001853
1854 .. versionadded:: 2.3
1855
1856
1857.. function:: nice(increment)
1858
1859 Add *increment* to the process's "niceness". Return the new niceness.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001860
Georg Brandl9af94982008-09-13 17:41:16 +00001861 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001862
1863
1864.. function:: plock(op)
1865
1866 Lock program segments into memory. The value of *op* (defined in
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001867 ``<sys/lock.h>``) determines which segments are locked.
1868
1869 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001870
1871
1872.. function:: popen(...)
1873 popen2(...)
1874 popen3(...)
1875 popen4(...)
1876 :noindex:
1877
1878 Run child processes, returning opened pipes for communications. These functions
1879 are described in section :ref:`os-newstreams`.
1880
1881
1882.. function:: spawnl(mode, path, ...)
1883 spawnle(mode, path, ..., env)
1884 spawnlp(mode, file, ...)
1885 spawnlpe(mode, file, ..., env)
1886 spawnv(mode, path, args)
1887 spawnve(mode, path, args, env)
1888 spawnvp(mode, file, args)
1889 spawnvpe(mode, file, args, env)
1890
1891 Execute the program *path* in a new process.
1892
1893 (Note that the :mod:`subprocess` module provides more powerful facilities for
1894 spawning new processes and retrieving their results; using that module is
R. David Murray9f8a51c2009-06-25 17:40:52 +00001895 preferable to using these functions. Check especially the
1896 :ref:`subprocess-replacements` section.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001897
Georg Brandlf725b952008-01-05 19:44:22 +00001898 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl8ec7f652007-08-15 14:28:01 +00001899 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1900 exits normally, or ``-signal``, where *signal* is the signal that killed the
Georg Brandlf725b952008-01-05 19:44:22 +00001901 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl8ec7f652007-08-15 14:28:01 +00001902 be used with the :func:`waitpid` function.
1903
Georg Brandlf725b952008-01-05 19:44:22 +00001904 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1905 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl8ec7f652007-08-15 14:28:01 +00001906 to work with if the number of parameters is fixed when the code is written; the
1907 individual parameters simply become additional parameters to the
Georg Brandlf725b952008-01-05 19:44:22 +00001908 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl8ec7f652007-08-15 14:28:01 +00001909 parameters is variable, with the arguments being passed in a list or tuple as
1910 the *args* parameter. In either case, the arguments to the child process must
1911 start with the name of the command being run.
1912
Georg Brandlf725b952008-01-05 19:44:22 +00001913 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001914 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1915 :envvar:`PATH` environment variable to locate the program *file*. When the
1916 environment is being replaced (using one of the :func:`spawn\*e` variants,
1917 discussed in the next paragraph), the new environment is used as the source of
1918 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1919 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1920 :envvar:`PATH` variable to locate the executable; *path* must contain an
1921 appropriate absolute or relative path.
1922
1923 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Georg Brandlf725b952008-01-05 19:44:22 +00001924 (note that these all end in "e"), the *env* parameter must be a mapping
Georg Brandlfb246c42008-04-19 16:58:28 +00001925 which is used to define the environment variables for the new process (they are
1926 used instead of the current process' environment); the functions
Georg Brandl8ec7f652007-08-15 14:28:01 +00001927 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
Georg Brandl8943caf2009-04-05 21:11:43 +00001928 the new process to inherit the environment of the current process. Note that
1929 keys and values in the *env* dictionary must be strings; invalid keys or
1930 values will cause the function to fail, with a return value of ``127``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001931
1932 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1933 equivalent::
1934
1935 import os
1936 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1937
1938 L = ['cp', 'index.html', '/dev/null']
1939 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1940
1941 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1942 and :func:`spawnvpe` are not available on Windows.
1943
1944 .. versionadded:: 1.6
1945
1946
1947.. data:: P_NOWAIT
1948 P_NOWAITO
1949
1950 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1951 functions. If either of these values is given, the :func:`spawn\*` functions
Georg Brandlf725b952008-01-05 19:44:22 +00001952 will return as soon as the new process has been created, with the process id as
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001953 the return value.
1954
1955 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001956
1957 .. versionadded:: 1.6
1958
1959
1960.. data:: P_WAIT
1961
1962 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1963 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1964 return until the new process has run to completion and will return the exit code
1965 of the process the run is successful, or ``-signal`` if a signal kills the
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001966 process.
1967
1968 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001969
1970 .. versionadded:: 1.6
1971
1972
1973.. data:: P_DETACH
1974 P_OVERLAY
1975
1976 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1977 functions. These are less portable than those listed above. :const:`P_DETACH`
1978 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1979 console of the calling process. If :const:`P_OVERLAY` is used, the current
1980 process will be replaced; the :func:`spawn\*` function will not return.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00001981
Georg Brandl8ec7f652007-08-15 14:28:01 +00001982 Availability: Windows.
1983
1984 .. versionadded:: 1.6
1985
1986
1987.. function:: startfile(path[, operation])
1988
1989 Start a file with its associated application.
1990
1991 When *operation* is not specified or ``'open'``, this acts like double-clicking
1992 the file in Windows Explorer, or giving the file name as an argument to the
1993 :program:`start` command from the interactive command shell: the file is opened
1994 with whatever application (if any) its extension is associated.
1995
1996 When another *operation* is given, it must be a "command verb" that specifies
1997 what should be done with the file. Common verbs documented by Microsoft are
1998 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1999 ``'find'`` (to be used on directories).
2000
2001 :func:`startfile` returns as soon as the associated application is launched.
2002 There is no option to wait for the application to close, and no way to retrieve
2003 the application's exit status. The *path* parameter is relative to the current
2004 directory. If you want to use an absolute path, make sure the first character
2005 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
2006 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002007 the path is properly encoded for Win32.
2008
2009 Availability: Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002010
2011 .. versionadded:: 2.0
2012
2013 .. versionadded:: 2.5
2014 The *operation* parameter.
2015
2016
2017.. function:: system(command)
2018
2019 Execute the command (a string) in a subshell. This is implemented by calling
Georg Brandl5d2eb342009-10-27 15:08:27 +00002020 the Standard C function :cfunc:`system`, and has the same limitations.
2021 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the
2022 executed command.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002023
2024 On Unix, the return value is the exit status of the process encoded in the
2025 format specified for :func:`wait`. Note that POSIX does not specify the meaning
2026 of the return value of the C :cfunc:`system` function, so the return value of
2027 the Python function is system-dependent.
2028
2029 On Windows, the return value is that returned by the system shell after running
2030 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
2031 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
2032 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
2033 the command run; on systems using a non-native shell, consult your shell
2034 documentation.
2035
Georg Brandl8ec7f652007-08-15 14:28:01 +00002036 The :mod:`subprocess` module provides more powerful facilities for spawning new
2037 processes and retrieving their results; using that module is preferable to using
Georg Brandl0ba92b22008-06-22 09:05:29 +00002038 this function. Use the :mod:`subprocess` module. Check especially the
2039 :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002040
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002041 Availability: Unix, Windows.
2042
Georg Brandl8ec7f652007-08-15 14:28:01 +00002043
2044.. function:: times()
2045
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002046 Return a 5-tuple of floating point numbers indicating accumulated (processor
2047 or other) times, in seconds. The items are: user time, system time,
2048 children's user time, children's system time, and elapsed real time since a
2049 fixed point in the past, in that order. See the Unix manual page
2050 :manpage:`times(2)` or the corresponding Windows Platform API documentation.
2051 On Windows, only the first two items are filled, the others are zero.
2052
2053 Availability: Unix, Windows
Georg Brandl8ec7f652007-08-15 14:28:01 +00002054
2055
2056.. function:: wait()
2057
2058 Wait for completion of a child process, and return a tuple containing its pid
2059 and exit status indication: a 16-bit number, whose low byte is the signal number
2060 that killed the process, and whose high byte is the exit status (if the signal
2061 number is zero); the high bit of the low byte is set if a core file was
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002062 produced.
2063
2064 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002065
2066
2067.. function:: waitpid(pid, options)
2068
2069 The details of this function differ on Unix and Windows.
2070
2071 On Unix: Wait for completion of a child process given by process id *pid*, and
2072 return a tuple containing its process id and exit status indication (encoded as
2073 for :func:`wait`). The semantics of the call are affected by the value of the
2074 integer *options*, which should be ``0`` for normal operation.
2075
2076 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
2077 that specific process. If *pid* is ``0``, the request is for the status of any
2078 child in the process group of the current process. If *pid* is ``-1``, the
2079 request pertains to any child of the current process. If *pid* is less than
2080 ``-1``, status is requested for any process in the process group ``-pid`` (the
2081 absolute value of *pid*).
2082
Gregory P. Smith59de7f52008-08-15 23:14:00 +00002083 An :exc:`OSError` is raised with the value of errno when the syscall
2084 returns -1.
2085
Georg Brandl8ec7f652007-08-15 14:28:01 +00002086 On Windows: Wait for completion of a process given by process handle *pid*, and
2087 return a tuple containing *pid*, and its exit status shifted left by 8 bits
2088 (shifting makes cross-platform use of the function easier). A *pid* less than or
2089 equal to ``0`` has no special meaning on Windows, and raises an exception. The
2090 value of integer *options* has no effect. *pid* can refer to any process whose
2091 id is known, not necessarily a child process. The :func:`spawn` functions called
2092 with :const:`P_NOWAIT` return suitable process handles.
2093
2094
2095.. function:: wait3([options])
2096
2097 Similar to :func:`waitpid`, except no process id argument is given and a
2098 3-element tuple containing the child's process id, exit status indication, and
2099 resource usage information is returned. Refer to :mod:`resource`.\
2100 :func:`getrusage` for details on resource usage information. The option
2101 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002102
Georg Brandl8ec7f652007-08-15 14:28:01 +00002103 Availability: Unix.
2104
2105 .. versionadded:: 2.5
2106
2107
2108.. function:: wait4(pid, options)
2109
2110 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
2111 process id, exit status indication, and resource usage information is returned.
2112 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
2113 information. The arguments to :func:`wait4` are the same as those provided to
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002114 :func:`waitpid`.
2115
2116 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002117
2118 .. versionadded:: 2.5
2119
2120
2121.. data:: WNOHANG
2122
2123 The option for :func:`waitpid` to return immediately if no child process status
2124 is available immediately. The function returns ``(0, 0)`` in this case.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002125
Georg Brandl9af94982008-09-13 17:41:16 +00002126 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002127
2128
2129.. data:: WCONTINUED
2130
2131 This option causes child processes to be reported if they have been continued
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002132 from a job control stop since their status was last reported.
2133
2134 Availability: Some Unix systems.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002135
2136 .. versionadded:: 2.3
2137
2138
2139.. data:: WUNTRACED
2140
2141 This option causes child processes to be reported if they have been stopped but
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002142 their current state has not been reported since they were stopped.
2143
2144 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002145
2146 .. versionadded:: 2.3
2147
2148The following functions take a process status code as returned by
2149:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
2150used to determine the disposition of a process.
2151
2152
2153.. function:: WCOREDUMP(status)
2154
Georg Brandlf725b952008-01-05 19:44:22 +00002155 Return ``True`` if a core dump was generated for the process, otherwise
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002156 return ``False``.
2157
2158 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002159
2160 .. versionadded:: 2.3
2161
2162
2163.. function:: WIFCONTINUED(status)
2164
Georg Brandlf725b952008-01-05 19:44:22 +00002165 Return ``True`` if the process has been continued from a job control stop,
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002166 otherwise return ``False``.
2167
2168 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002169
2170 .. versionadded:: 2.3
2171
2172
2173.. function:: WIFSTOPPED(status)
2174
Georg Brandlf725b952008-01-05 19:44:22 +00002175 Return ``True`` if the process has been stopped, otherwise return
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002176 ``False``.
2177
2178 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002179
2180
2181.. function:: WIFSIGNALED(status)
2182
Georg Brandlf725b952008-01-05 19:44:22 +00002183 Return ``True`` if the process exited due to a signal, otherwise return
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002184 ``False``.
2185
2186 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002187
2188
2189.. function:: WIFEXITED(status)
2190
Georg Brandlf725b952008-01-05 19:44:22 +00002191 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002192 otherwise return ``False``.
2193
2194 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002195
2196
2197.. function:: WEXITSTATUS(status)
2198
2199 If ``WIFEXITED(status)`` is true, return the integer parameter to the
2200 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002201
Georg Brandl9af94982008-09-13 17:41:16 +00002202 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002203
2204
2205.. function:: WSTOPSIG(status)
2206
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002207 Return the signal which caused the process to stop.
2208
2209 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002210
2211
2212.. function:: WTERMSIG(status)
2213
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002214 Return the signal which caused the process to exit.
2215
2216 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002217
2218
2219.. _os-path:
2220
2221Miscellaneous System Information
2222--------------------------------
2223
2224
2225.. function:: confstr(name)
2226
2227 Return string-valued system configuration values. *name* specifies the
2228 configuration value to retrieve; it may be a string which is the name of a
2229 defined system value; these names are specified in a number of standards (POSIX,
2230 Unix 95, Unix 98, and others). Some platforms define additional names as well.
2231 The names known to the host operating system are given as the keys of the
2232 ``confstr_names`` dictionary. For configuration variables not included in that
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002233 mapping, passing an integer for *name* is also accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002234
2235 If the configuration value specified by *name* isn't defined, ``None`` is
2236 returned.
2237
2238 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2239 specific value for *name* is not supported by the host system, even if it is
2240 included in ``confstr_names``, an :exc:`OSError` is raised with
2241 :const:`errno.EINVAL` for the error number.
2242
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002243 Availability: Unix
2244
Georg Brandl8ec7f652007-08-15 14:28:01 +00002245
2246.. data:: confstr_names
2247
2248 Dictionary mapping names accepted by :func:`confstr` to the integer values
2249 defined for those names by the host operating system. This can be used to
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002250 determine the set of names known to the system.
2251
2252 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002253
2254
2255.. function:: getloadavg()
2256
Georg Brandl57fe0f22008-01-12 10:53:29 +00002257 Return the number of processes in the system run queue averaged over the last
2258 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002259 unobtainable.
2260
2261 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002262
2263 .. versionadded:: 2.3
2264
2265
2266.. function:: sysconf(name)
2267
2268 Return integer-valued system configuration values. If the configuration value
2269 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2270 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2271 provides information on the known names is given by ``sysconf_names``.
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002272
Georg Brandl9af94982008-09-13 17:41:16 +00002273 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002274
2275
2276.. data:: sysconf_names
2277
2278 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2279 defined for those names by the host operating system. This can be used to
Benjamin Peterson2f9134b2010-05-06 23:04:44 +00002280 determine the set of names known to the system.
2281
2282 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002283
Georg Brandlf725b952008-01-05 19:44:22 +00002284The following data values are used to support path manipulation operations. These
Georg Brandl8ec7f652007-08-15 14:28:01 +00002285are defined for all platforms.
2286
2287Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2288
2289
2290.. data:: curdir
2291
2292 The constant string used by the operating system to refer to the current
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:: pardir
2298
2299 The constant string used by the operating system to refer to the parent
Georg Brandl9af94982008-09-13 17:41:16 +00002300 directory. This is ``'..'`` for Windows and POSIX. Also available via
2301 :mod:`os.path`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002302
2303
2304.. data:: sep
2305
Georg Brandl9af94982008-09-13 17:41:16 +00002306 The character used by the operating system to separate pathname components.
2307 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
2308 is not sufficient to be able to parse or concatenate pathnames --- use
Georg Brandl8ec7f652007-08-15 14:28:01 +00002309 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2310 useful. Also available via :mod:`os.path`.
2311
2312
2313.. data:: altsep
2314
2315 An alternative character used by the operating system to separate pathname
2316 components, or ``None`` if only one separator character exists. This is set to
2317 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2318 :mod:`os.path`.
2319
2320
2321.. data:: extsep
2322
2323 The character which separates the base filename from the extension; for example,
2324 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2325
2326 .. versionadded:: 2.2
2327
2328
2329.. data:: pathsep
2330
2331 The character conventionally used by the operating system to separate search
2332 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2333 Windows. Also available via :mod:`os.path`.
2334
2335
2336.. data:: defpath
2337
2338 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
2339 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
2340
2341
2342.. data:: linesep
2343
2344 The string used to separate (or, rather, terminate) lines on the current
Georg Brandl9af94982008-09-13 17:41:16 +00002345 platform. This may be a single character, such as ``'\n'`` for POSIX, or
2346 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
2347 *os.linesep* as a line terminator when writing files opened in text mode (the
2348 default); use a single ``'\n'`` instead, on all platforms.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002349
2350
2351.. data:: devnull
2352
Georg Brandl9af94982008-09-13 17:41:16 +00002353 The file path of the null device. For example: ``'/dev/null'`` for POSIX.
2354 Also available via :mod:`os.path`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002355
2356 .. versionadded:: 2.4
2357
2358
2359.. _os-miscfunc:
2360
2361Miscellaneous Functions
2362-----------------------
2363
2364
2365.. function:: urandom(n)
2366
2367 Return a string of *n* random bytes suitable for cryptographic use.
2368
2369 This function returns random bytes from an OS-specific randomness source. The
2370 returned data should be unpredictable enough for cryptographic applications,
2371 though its exact quality depends on the OS implementation. On a UNIX-like
2372 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
2373 If a randomness source is not found, :exc:`NotImplementedError` will be raised.
2374
2375 .. versionadded:: 2.4
2376