blob: c2ea1be951bb1fb568287f4e27df07cfdbf5cfd9 [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 Brandlc51d1f02009-12-19 18:16:31 +000016Notes on the availability of these functions:
Georg Brandl8ec7f652007-08-15 14:28:01 +000017
Georg Brandlc51d1f02009-12-19 18:16:31 +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 Brandlc51d1f02009-12-19 18:16:31 +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 Brandlc51d1f02009-12-19 18:16:31 +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 Peterson328e3772010-05-06 22:49:28 +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 Brandlc51d1f02009-12-19 18:16:31 +000052 The name of the operating system dependent module imported. The following
Ronald Oussoren9545a232010-05-05 19:09:31 +000053 names have currently been registered: ``'posix'``, ``'nt'``,
Georg Brandlc51d1f02009-12-19 18:16:31 +000054 ``'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 Peterson328e3772010-05-06 22:49:28 +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 Peterson328e3772010-05-06 22:49:28 +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 Peterson328e3772010-05-06 22:49:28 +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 Peterson328e3772010-05-06 22:49:28 +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 Peterson328e3772010-05-06 22:49:28 +0000150
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151 Availability: Unix.
152
153
Antoine Pitrou30b3b352009-12-02 20:37:54 +0000154.. function:: initgroups(username, gid)
155
156 Call the system initgroups() to initialize the group access list with all of
157 the groups of which the specified username is a member, plus the specified
Benjamin Peterson328e3772010-05-06 22:49:28 +0000158 group id.
159
160 Availability: Unix.
Antoine Pitrou30b3b352009-12-02 20:37:54 +0000161
162 .. versionadded:: 2.7
163
164
Georg Brandl8ec7f652007-08-15 14:28:01 +0000165.. function:: getlogin()
166
167 Return the name of the user logged in on the controlling terminal of the
168 process. For most purposes, it is more useful to use the environment variable
169 :envvar:`LOGNAME` to find out who the user is, or
170 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
Benjamin Peterson328e3772010-05-06 22:49:28 +0000171 effective user id.
172
173 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000174
175
176.. function:: getpgid(pid)
177
178 Return the process group id of the process with process id *pid*. If *pid* is 0,
Benjamin Peterson328e3772010-05-06 22:49:28 +0000179 the process group id of the current process is returned.
180
181 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
183 .. versionadded:: 2.3
184
185
186.. function:: getpgrp()
187
188 .. index:: single: process; group
189
Benjamin Peterson328e3772010-05-06 22:49:28 +0000190 Return the id of the current process group.
191
192 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193
194
195.. function:: getpid()
196
197 .. index:: single: process; id
198
Benjamin Peterson328e3772010-05-06 22:49:28 +0000199 Return the current process id.
200
201 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202
203
204.. function:: getppid()
205
206 .. index:: single: process; id of parent
207
Benjamin Peterson328e3772010-05-06 22:49:28 +0000208 Return the parent's process id.
209
210 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211
Georg Brandl8d8f8742009-11-28 11:11:50 +0000212
Gregory P. Smith761ae0b2009-11-27 17:51:12 +0000213.. function:: getresuid()
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000214
215 Return a tuple (ruid, euid, suid) denoting the current process's
Benjamin Peterson328e3772010-05-06 22:49:28 +0000216 real, effective, and saved user ids.
217
218 Availability: Unix.
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000219
Georg Brandl8d8f8742009-11-28 11:11:50 +0000220 .. versionadded:: 2.7
221
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000222
Gregory P. Smith761ae0b2009-11-27 17:51:12 +0000223.. function:: getresgid()
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000224
225 Return a tuple (rgid, egid, sgid) denoting the current process's
Georg Brandl21946af2010-10-06 09:28:45 +0000226 real, effective, and saved group ids.
Benjamin Peterson328e3772010-05-06 22:49:28 +0000227
228 Availability: Unix.
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000229
Georg Brandl8d8f8742009-11-28 11:11:50 +0000230 .. versionadded:: 2.7
231
Georg Brandl8ec7f652007-08-15 14:28:01 +0000232
233.. function:: getuid()
234
235 .. index:: single: user; id
236
Benjamin Peterson328e3772010-05-06 22:49:28 +0000237 Return the current process's user id.
238
239 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000240
241
242.. function:: getenv(varname[, value])
243
244 Return the value of the environment variable *varname* if it exists, or *value*
Benjamin Peterson328e3772010-05-06 22:49:28 +0000245 if it doesn't. *value* defaults to ``None``.
246
247 Availability: most flavors of Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000248
249
250.. function:: putenv(varname, value)
251
252 .. index:: single: environment variables; setting
253
254 Set the environment variable named *varname* to the string *value*. Such
255 changes to the environment affect subprocesses started with :func:`os.system`,
Benjamin Peterson328e3772010-05-06 22:49:28 +0000256 :func:`popen` or :func:`fork` and :func:`execv`.
257
258 Availability: most flavors of Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259
260 .. note::
261
Georg Brandl9af94982008-09-13 17:41:16 +0000262 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
263 cause memory leaks. Refer to the system documentation for putenv.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000264
265 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
266 automatically translated into corresponding calls to :func:`putenv`; however,
267 calls to :func:`putenv` don't update ``os.environ``, so it is actually
268 preferable to assign to items of ``os.environ``.
269
270
271.. function:: setegid(egid)
272
Benjamin Peterson328e3772010-05-06 22:49:28 +0000273 Set the current process's effective group id.
274
275 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000276
277
278.. function:: seteuid(euid)
279
Benjamin Peterson328e3772010-05-06 22:49:28 +0000280 Set the current process's effective user id.
281
282 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
284
285.. function:: setgid(gid)
286
Benjamin Peterson328e3772010-05-06 22:49:28 +0000287 Set the current process' group id.
288
289 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000290
291
292.. function:: setgroups(groups)
293
294 Set the list of supplemental group ids associated with the current process to
295 *groups*. *groups* must be a sequence, and each element must be an integer
Georg Brandlf725b952008-01-05 19:44:22 +0000296 identifying a group. This operation is typically available only to the superuser.
Benjamin Peterson328e3772010-05-06 22:49:28 +0000297
Georg Brandl8ec7f652007-08-15 14:28:01 +0000298 Availability: Unix.
299
300 .. versionadded:: 2.2
301
302
303.. function:: setpgrp()
304
Georg Brandlf725b952008-01-05 19:44:22 +0000305 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306 which version is implemented (if any). See the Unix manual for the semantics.
Benjamin Peterson328e3772010-05-06 22:49:28 +0000307
Georg Brandl8ec7f652007-08-15 14:28:01 +0000308 Availability: Unix.
309
310
311.. function:: setpgid(pid, pgrp)
312
Georg Brandlf725b952008-01-05 19:44:22 +0000313 Call the system call :cfunc:`setpgid` to set the process group id of the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000314 process with id *pid* to the process group with id *pgrp*. See the Unix manual
Benjamin Peterson328e3772010-05-06 22:49:28 +0000315 for the semantics.
316
317 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000318
319
Georg Brandl8ec7f652007-08-15 14:28:01 +0000320.. function:: setregid(rgid, egid)
321
Benjamin Peterson328e3772010-05-06 22:49:28 +0000322 Set the current process's real and effective group ids.
323
324 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000325
Georg Brandl8d8f8742009-11-28 11:11:50 +0000326
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000327.. function:: setresgid(rgid, egid, sgid)
328
329 Set the current process's real, effective, and saved group ids.
Benjamin Peterson328e3772010-05-06 22:49:28 +0000330
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000331 Availability: Unix.
332
Georg Brandl8d8f8742009-11-28 11:11:50 +0000333 .. versionadded:: 2.7
334
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000335
336.. function:: setresuid(ruid, euid, suid)
337
338 Set the current process's real, effective, and saved user ids.
Benjamin Peterson328e3772010-05-06 22:49:28 +0000339
Georg Brandl09302282010-10-06 09:32:48 +0000340 Availability: Unix.
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000341
Georg Brandl8d8f8742009-11-28 11:11:50 +0000342 .. versionadded:: 2.7
343
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000344
345.. function:: setreuid(ruid, euid)
346
Benjamin Peterson328e3772010-05-06 22:49:28 +0000347 Set the current process's real and effective user ids.
348
349 Availability: Unix.
Martin v. Löwis50ea4562009-11-27 13:56:01 +0000350
Georg Brandl8ec7f652007-08-15 14:28:01 +0000351
352.. function:: getsid(pid)
353
Georg Brandlf725b952008-01-05 19:44:22 +0000354 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
Benjamin Peterson328e3772010-05-06 22:49:28 +0000355
Georg Brandl8ec7f652007-08-15 14:28:01 +0000356 Availability: Unix.
357
358 .. versionadded:: 2.4
359
360
361.. function:: setsid()
362
Georg Brandlf725b952008-01-05 19:44:22 +0000363 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
Benjamin Peterson328e3772010-05-06 22:49:28 +0000364
Georg Brandl8ec7f652007-08-15 14:28:01 +0000365 Availability: Unix.
366
367
368.. function:: setuid(uid)
369
370 .. index:: single: user; id, setting
371
Benjamin Peterson328e3772010-05-06 22:49:28 +0000372 Set the current process's user id.
373
374 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000375
Georg Brandl8ec7f652007-08-15 14:28:01 +0000376
Georg Brandlb19be572007-12-29 10:57:00 +0000377.. placed in this section since it relates to errno.... a little weak
Georg Brandl8ec7f652007-08-15 14:28:01 +0000378.. function:: strerror(code)
379
380 Return the error message corresponding to the error code in *code*.
Georg Brandl3fc974f2008-05-11 21:16:37 +0000381 On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
Benjamin Peterson328e3772010-05-06 22:49:28 +0000382 error number, :exc:`ValueError` is raised.
383
384 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000385
386
387.. function:: umask(mask)
388
Benjamin Peterson328e3772010-05-06 22:49:28 +0000389 Set the current numeric umask and return the previous umask.
390
391 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000392
393
394.. function:: uname()
395
396 .. index::
397 single: gethostname() (in module socket)
398 single: gethostbyaddr() (in module socket)
399
400 Return a 5-tuple containing information identifying the current operating
401 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
402 machine)``. Some systems truncate the nodename to 8 characters or to the
403 leading component; a better way to get the hostname is
404 :func:`socket.gethostname` or even
Benjamin Peterson328e3772010-05-06 22:49:28 +0000405 ``socket.gethostbyaddr(socket.gethostname())``.
406
407 Availability: recent flavors of Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000408
409
410.. function:: unsetenv(varname)
411
412 .. index:: single: environment variables; deleting
413
414 Unset (delete) the environment variable named *varname*. Such changes to the
415 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
Benjamin Peterson328e3772010-05-06 22:49:28 +0000416 :func:`fork` and :func:`execv`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000417
418 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
419 automatically translated into a corresponding call to :func:`unsetenv`; however,
420 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
421 preferable to delete items of ``os.environ``.
422
Benjamin Peterson328e3772010-05-06 22:49:28 +0000423 Availability: most flavors of Unix, Windows.
424
Georg Brandl8ec7f652007-08-15 14:28:01 +0000425
426.. _os-newstreams:
427
428File Object Creation
429--------------------
430
431These functions create new file objects. (See also :func:`open`.)
432
433
434.. function:: fdopen(fd[, mode[, bufsize]])
435
436 .. index:: single: I/O control; buffering
437
438 Return an open file object connected to the file descriptor *fd*. The *mode*
439 and *bufsize* arguments have the same meaning as the corresponding arguments to
Benjamin Peterson328e3772010-05-06 22:49:28 +0000440 the built-in :func:`open` function.
441
442 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000443
444 .. versionchanged:: 2.3
445 When specified, the *mode* argument must now start with one of the letters
446 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
447
448 .. versionchanged:: 2.5
449 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
450 set on the file descriptor (which the :cfunc:`fdopen` implementation already
451 does on most platforms).
452
453
454.. function:: popen(command[, mode[, bufsize]])
455
456 Open a pipe to or from *command*. The return value is an open file object
457 connected to the pipe, which can be read or written depending on whether *mode*
458 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
459 the corresponding argument to the built-in :func:`open` function. The exit
460 status of the command (encoded in the format specified for :func:`wait`) is
Georg Brandl012408c2009-05-22 09:43:17 +0000461 available as the return value of the :meth:`~file.close` method of the file object,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000462 except that when the exit status is zero (termination without errors), ``None``
Benjamin Peterson328e3772010-05-06 22:49:28 +0000463 is returned.
464
465 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000466
467 .. deprecated:: 2.6
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000468 This function is obsolete. Use the :mod:`subprocess` module. Check
Georg Brandl0ba92b22008-06-22 09:05:29 +0000469 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000470
471 .. versionchanged:: 2.0
472 This function worked unreliably under Windows in earlier versions of Python.
473 This was due to the use of the :cfunc:`_popen` function from the libraries
474 provided with Windows. Newer versions of Python do not use the broken
475 implementation from the Windows libraries.
476
477
478.. function:: tmpfile()
479
480 Return a new file object opened in update mode (``w+b``). The file has no
481 directory entries associated with it and will be automatically deleted once
Benjamin Peterson328e3772010-05-06 22:49:28 +0000482 there are no file descriptors for the file.
483
484 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000485
486There are a number of different :func:`popen\*` functions that provide slightly
487different ways to create subprocesses.
488
489.. deprecated:: 2.6
490 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
491 module.
492
493For each of the :func:`popen\*` variants, if *bufsize* is specified, it
494specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
495string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
496file objects should be opened in binary or text mode. The default value for
497*mode* is ``'t'``.
498
499Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
500case arguments will be passed directly to the program without shell intervention
501(as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
502(as with :func:`os.system`).
503
504These methods do not make it possible to retrieve the exit status from the child
505processes. The only way to control the input and output streams and also
506retrieve the return codes is to use the :mod:`subprocess` module; these are only
507available on Unix.
508
509For a discussion of possible deadlock conditions related to the use of these
510functions, see :ref:`popen2-flow-control`.
511
512
513.. function:: popen2(cmd[, mode[, bufsize]])
514
Georg Brandlf725b952008-01-05 19:44:22 +0000515 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000516 child_stdout)``.
517
518 .. deprecated:: 2.6
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000519 This function is obsolete. Use the :mod:`subprocess` module. Check
Georg Brandl0ba92b22008-06-22 09:05:29 +0000520 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000521
Georg Brandl9af94982008-09-13 17:41:16 +0000522 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000523
524 .. versionadded:: 2.0
525
526
527.. function:: popen3(cmd[, mode[, bufsize]])
528
Georg Brandlf725b952008-01-05 19:44:22 +0000529 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000530 child_stdout, child_stderr)``.
531
532 .. deprecated:: 2.6
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000533 This function is obsolete. Use the :mod:`subprocess` module. Check
Georg Brandl0ba92b22008-06-22 09:05:29 +0000534 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000535
Georg Brandl9af94982008-09-13 17:41:16 +0000536 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000537
538 .. versionadded:: 2.0
539
540
541.. function:: popen4(cmd[, mode[, bufsize]])
542
Georg Brandlf725b952008-01-05 19:44:22 +0000543 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000544 child_stdout_and_stderr)``.
545
546 .. deprecated:: 2.6
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000547 This function is obsolete. Use the :mod:`subprocess` module. Check
Georg Brandl0ba92b22008-06-22 09:05:29 +0000548 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000549
Georg Brandl9af94982008-09-13 17:41:16 +0000550 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000551
552 .. versionadded:: 2.0
553
554(Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
555point of view of the child process, so *child_stdin* is the child's standard
556input.)
557
558This functionality is also available in the :mod:`popen2` module using functions
559of the same names, but the return values of those functions have a different
560order.
561
562
563.. _os-fd-ops:
564
565File Descriptor Operations
566--------------------------
567
568These functions operate on I/O streams referenced using file descriptors.
569
570File descriptors are small integers corresponding to a file that has been opened
571by the current process. For example, standard input is usually file descriptor
5720, standard output is 1, and standard error is 2. Further files opened by a
573process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
574is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
575by file descriptors.
576
Georg Brandl49b91922010-04-02 08:39:09 +0000577The :meth:`~file.fileno` method can be used to obtain the file descriptor
578associated with a file object when required. Note that using the file
579descriptor directly will bypass the file object methods, ignoring aspects such
580as internal buffering of data.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000581
582.. function:: close(fd)
583
Benjamin Peterson328e3772010-05-06 22:49:28 +0000584 Close file descriptor *fd*.
585
586 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000587
588 .. note::
589
590 This function is intended for low-level I/O and must be applied to a file
Georg Brandl012408c2009-05-22 09:43:17 +0000591 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
Georg Brandl8ec7f652007-08-15 14:28:01 +0000592 object" returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandl012408c2009-05-22 09:43:17 +0000593 :func:`fdopen`, use its :meth:`~file.close` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000594
595
Georg Brandl309501a2008-01-19 20:22:13 +0000596.. function:: closerange(fd_low, fd_high)
597
598 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
Benjamin Peterson328e3772010-05-06 22:49:28 +0000599 ignoring errors. Equivalent to::
Georg Brandl309501a2008-01-19 20:22:13 +0000600
601 for fd in xrange(fd_low, fd_high):
602 try:
603 os.close(fd)
604 except OSError:
605 pass
606
Benjamin Peterson328e3772010-05-06 22:49:28 +0000607 Availability: Unix, Windows.
608
Georg Brandl309501a2008-01-19 20:22:13 +0000609 .. versionadded:: 2.6
610
611
Georg Brandl8ec7f652007-08-15 14:28:01 +0000612.. function:: dup(fd)
613
Benjamin Peterson328e3772010-05-06 22:49:28 +0000614 Return a duplicate of file descriptor *fd*.
615
616 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000617
618
619.. function:: dup2(fd, fd2)
620
621 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
Benjamin Peterson328e3772010-05-06 22:49:28 +0000622
Georg Brandl9af94982008-09-13 17:41:16 +0000623 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000624
625
Christian Heimes36281872007-11-30 21:11:28 +0000626.. function:: fchmod(fd, mode)
627
628 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
Benjamin Peterson328e3772010-05-06 22:49:28 +0000629 for :func:`chmod` for possible values of *mode*.
630
631 Availability: Unix.
Christian Heimes36281872007-11-30 21:11:28 +0000632
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000633 .. versionadded:: 2.6
634
Christian Heimes36281872007-11-30 21:11:28 +0000635
636.. function:: fchown(fd, uid, gid)
637
638 Change the owner and group id of the file given by *fd* to the numeric *uid*
639 and *gid*. To leave one of the ids unchanged, set it to -1.
Benjamin Peterson328e3772010-05-06 22:49:28 +0000640
Christian Heimes36281872007-11-30 21:11:28 +0000641 Availability: Unix.
642
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000643 .. versionadded:: 2.6
644
Christian Heimes36281872007-11-30 21:11:28 +0000645
Georg Brandl8ec7f652007-08-15 14:28:01 +0000646.. function:: fdatasync(fd)
647
648 Force write of file with filedescriptor *fd* to disk. Does not force update of
Benjamin Peterson328e3772010-05-06 22:49:28 +0000649 metadata.
650
651 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000652
Benjamin Petersonecf3c622009-05-30 03:10:52 +0000653 .. note::
654 This function is not available on MacOS.
655
Georg Brandl8ec7f652007-08-15 14:28:01 +0000656
657.. function:: fpathconf(fd, name)
658
659 Return system configuration information relevant to an open file. *name*
660 specifies the configuration value to retrieve; it may be a string which is the
661 name of a defined system value; these names are specified in a number of
662 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
663 additional names as well. The names known to the host operating system are
664 given in the ``pathconf_names`` dictionary. For configuration variables not
665 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000666
667 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
668 specific value for *name* is not supported by the host system, even if it is
669 included in ``pathconf_names``, an :exc:`OSError` is raised with
670 :const:`errno.EINVAL` for the error number.
671
Benjamin Peterson328e3772010-05-06 22:49:28 +0000672 Availability: Unix.
673
Georg Brandl8ec7f652007-08-15 14:28:01 +0000674
675.. function:: fstat(fd)
676
R. David Murray561b96f2011-02-11 17:25:54 +0000677 Return status for file descriptor *fd*, like :func:`~os.stat`.
Benjamin Peterson328e3772010-05-06 22:49:28 +0000678
679 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000680
681
682.. function:: fstatvfs(fd)
683
684 Return information about the filesystem containing the file associated with file
Benjamin Peterson328e3772010-05-06 22:49:28 +0000685 descriptor *fd*, like :func:`statvfs`.
686
687 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000688
689
690.. function:: fsync(fd)
691
692 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
693 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
694
695 If you're starting with a Python file object *f*, first do ``f.flush()``, and
696 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
Benjamin Peterson328e3772010-05-06 22:49:28 +0000697 with *f* are written to disk.
698
699 Availability: Unix, and Windows starting in 2.2.3.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000700
701
702.. function:: ftruncate(fd, length)
703
704 Truncate the file corresponding to file descriptor *fd*, so that it is at most
Benjamin Peterson328e3772010-05-06 22:49:28 +0000705 *length* bytes in size.
706
707 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000708
709
710.. function:: isatty(fd)
711
712 Return ``True`` if the file descriptor *fd* is open and connected to a
Benjamin Peterson328e3772010-05-06 22:49:28 +0000713 tty(-like) device, else ``False``.
714
715 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000716
717
718.. function:: lseek(fd, pos, how)
719
Georg Brandlf725b952008-01-05 19:44:22 +0000720 Set the current position of file descriptor *fd* to position *pos*, modified
721 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
722 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
723 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Benjamin Peterson328e3772010-05-06 22:49:28 +0000724 the file.
725
726 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000727
728
Georg Brandl6c50efe2010-04-14 13:50:31 +0000729.. data:: SEEK_SET
730 SEEK_CUR
731 SEEK_END
732
733 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
Benjamin Peterson328e3772010-05-06 22:49:28 +0000734 respectively.
735
736 Availability: Windows, Unix.
Georg Brandl6c50efe2010-04-14 13:50:31 +0000737
738 .. versionadded:: 2.5
739
740
Georg Brandl8ec7f652007-08-15 14:28:01 +0000741.. function:: open(file, flags[, mode])
742
743 Open the file *file* and set various flags according to *flags* and possibly its
744 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
745 current umask value is first masked out. Return the file descriptor for the
Benjamin Peterson328e3772010-05-06 22:49:28 +0000746 newly opened file.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000747
748 For a description of the flag and mode values, see the C run-time documentation;
749 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
Georg Brandl4a589c32010-04-14 19:16:38 +0000750 this module too (see :ref:`open-constants`). In particular, on Windows adding
751 :const:`O_BINARY` is needed to open files in binary mode.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000752
Benjamin Peterson328e3772010-05-06 22:49:28 +0000753 Availability: Unix, Windows.
754
Georg Brandl8ec7f652007-08-15 14:28:01 +0000755 .. note::
756
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000757 This function is intended for low-level I/O. For normal usage, use the
758 built-in function :func:`open`, which returns a "file object" with
Jeroen Ruigrok van der Werven320477e2010-07-13 15:08:30 +0000759 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000760 wrap a file descriptor in a "file object", use :func:`fdopen`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000761
762
763.. function:: openpty()
764
765 .. index:: module: pty
766
767 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
768 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Benjamin Peterson328e3772010-05-06 22:49:28 +0000769 approach, use the :mod:`pty` module.
770
771 Availability: some flavors of Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000772
773
774.. function:: pipe()
775
776 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
Benjamin Peterson328e3772010-05-06 22:49:28 +0000777 and writing, respectively.
778
779 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000780
781
782.. function:: read(fd, n)
783
784 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
785 bytes read. If the end of the file referred to by *fd* has been reached, an
Benjamin Peterson328e3772010-05-06 22:49:28 +0000786 empty string is returned.
787
788 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000789
790 .. note::
791
792 This function is intended for low-level I/O and must be applied to a file
Georg Brandl012408c2009-05-22 09:43:17 +0000793 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a "file object"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000794 returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandl012408c2009-05-22 09:43:17 +0000795 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
796 :meth:`~file.readline` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000797
798
799.. function:: tcgetpgrp(fd)
800
801 Return the process group associated with the terminal given by *fd* (an open
Benjamin Peterson328e3772010-05-06 22:49:28 +0000802 file descriptor as returned by :func:`os.open`).
803
804 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000805
806
807.. function:: tcsetpgrp(fd, pg)
808
809 Set the process group associated with the terminal given by *fd* (an open file
Benjamin Peterson328e3772010-05-06 22:49:28 +0000810 descriptor as returned by :func:`os.open`) to *pg*.
811
812 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000813
814
815.. function:: ttyname(fd)
816
817 Return a string which specifies the terminal device associated with
Georg Brandlbb75e4e2007-10-21 10:46:24 +0000818 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Benjamin Peterson328e3772010-05-06 22:49:28 +0000819 exception is raised.
820
821 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000822
823
824.. function:: write(fd, str)
825
826 Write the string *str* to file descriptor *fd*. Return the number of bytes
Benjamin Peterson328e3772010-05-06 22:49:28 +0000827 actually written.
828
829 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000830
831 .. note::
832
833 This function is intended for low-level I/O and must be applied to a file
Georg Brandl012408c2009-05-22 09:43:17 +0000834 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
Georg Brandl8ec7f652007-08-15 14:28:01 +0000835 object" returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandl012408c2009-05-22 09:43:17 +0000836 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
837 :meth:`~file.write` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000838
Georg Brandl6c50efe2010-04-14 13:50:31 +0000839
840.. _open-constants:
841
842``open()`` flag constants
843~~~~~~~~~~~~~~~~~~~~~~~~~
844
Georg Brandl0c880bd2008-12-05 08:02:17 +0000845The following constants are options for the *flags* parameter to the
Georg Brandl012408c2009-05-22 09:43:17 +0000846:func:`~os.open` function. They can be combined using the bitwise OR operator
Georg Brandl0c880bd2008-12-05 08:02:17 +0000847``|``. Some of them are not available on all platforms. For descriptions of
Georg Brandle70ff4b2008-12-05 09:25:32 +0000848their availability and use, consult the :manpage:`open(2)` manual page on Unix
Doug Hellmann1d18b5b2009-09-20 20:44:13 +0000849or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000850
851
852.. data:: O_RDONLY
853 O_WRONLY
854 O_RDWR
855 O_APPEND
856 O_CREAT
857 O_EXCL
858 O_TRUNC
859
Georg Brandl0c880bd2008-12-05 08:02:17 +0000860 These constants are available on Unix and Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000861
862
863.. data:: O_DSYNC
864 O_RSYNC
865 O_SYNC
866 O_NDELAY
867 O_NONBLOCK
868 O_NOCTTY
869 O_SHLOCK
870 O_EXLOCK
871
Georg Brandl0c880bd2008-12-05 08:02:17 +0000872 These constants are only available on Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000873
874
875.. data:: O_BINARY
Georg Brandlb67da6e2007-11-24 13:56:09 +0000876 O_NOINHERIT
Georg Brandl8ec7f652007-08-15 14:28:01 +0000877 O_SHORT_LIVED
878 O_TEMPORARY
879 O_RANDOM
880 O_SEQUENTIAL
881 O_TEXT
882
Georg Brandl0c880bd2008-12-05 08:02:17 +0000883 These constants are only available on Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000884
885
Georg Brandlae6b9f32008-05-16 13:41:26 +0000886.. data:: O_ASYNC
887 O_DIRECT
Georg Brandlb67da6e2007-11-24 13:56:09 +0000888 O_DIRECTORY
889 O_NOFOLLOW
890 O_NOATIME
891
Georg Brandl0c880bd2008-12-05 08:02:17 +0000892 These constants are GNU extensions and not present if they are not defined by
893 the C library.
Georg Brandlb67da6e2007-11-24 13:56:09 +0000894
895
Georg Brandl8ec7f652007-08-15 14:28:01 +0000896.. _os-file-dir:
897
898Files and Directories
899---------------------
900
Georg Brandl8ec7f652007-08-15 14:28:01 +0000901.. function:: access(path, mode)
902
903 Use the real uid/gid to test for access to *path*. Note that most operations
904 will use the effective uid/gid, therefore this routine can be used in a
905 suid/sgid environment to test if the invoking user has the specified access to
906 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
907 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
908 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
909 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
Benjamin Peterson328e3772010-05-06 22:49:28 +0000910 information.
911
912 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000913
914 .. note::
915
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000916 Using :func:`access` to check if a user is authorized to e.g. open a file
917 before actually doing so using :func:`open` creates a security hole,
918 because the user might exploit the short time interval between checking
Benjamin Peterson30e10d82011-05-20 11:41:13 -0500919 and opening the file to manipulate it. It's preferable to use :term:`EAFP`
920 techniques. For example::
921
922 if os.access("myfile", os.R_OK):
923 with open("myfile") as fp:
924 return fp.read()
925 return "some default data"
926
927 is better written as::
928
929 try:
930 fp = open("myfile")
Benjamin Petersonce77def2011-05-20 11:49:06 -0500931 except IOError as e:
Benjamin Peterson30e10d82011-05-20 11:41:13 -0500932 if e.errno == errno.EACCESS:
933 return "some default data"
934 # Not a permission error.
935 raise
936 else:
937 with fp:
938 return fp.read()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000939
940 .. note::
941
942 I/O operations may fail even when :func:`access` indicates that they would
943 succeed, particularly for operations on network filesystems which may have
944 permissions semantics beyond the usual POSIX permission-bit model.
945
946
947.. data:: F_OK
948
949 Value to pass as the *mode* parameter of :func:`access` to test the existence of
950 *path*.
951
952
953.. data:: R_OK
954
955 Value to include in the *mode* parameter of :func:`access` to test the
956 readability of *path*.
957
958
959.. data:: W_OK
960
961 Value to include in the *mode* parameter of :func:`access` to test the
962 writability of *path*.
963
964
965.. data:: X_OK
966
967 Value to include in the *mode* parameter of :func:`access` to determine if
968 *path* can be executed.
969
970
971.. function:: chdir(path)
972
973 .. index:: single: directory; changing
974
Benjamin Peterson328e3772010-05-06 22:49:28 +0000975 Change the current working directory to *path*.
976
977 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000978
979
980.. function:: fchdir(fd)
981
982 Change the current working directory to the directory represented by the file
983 descriptor *fd*. The descriptor must refer to an opened directory, not an open
Benjamin Peterson328e3772010-05-06 22:49:28 +0000984 file.
985
986 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000987
988 .. versionadded:: 2.3
989
990
991.. function:: getcwd()
992
Benjamin Peterson328e3772010-05-06 22:49:28 +0000993 Return a string representing the current working directory.
994
995 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000996
997
998.. function:: getcwdu()
999
1000 Return a Unicode object representing the current working directory.
Benjamin Peterson328e3772010-05-06 22:49:28 +00001001
Georg Brandl9af94982008-09-13 17:41:16 +00001002 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001003
1004 .. versionadded:: 2.3
1005
1006
1007.. function:: chflags(path, flags)
1008
1009 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
1010 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
1011
R David Murrayefd8bab2011-03-10 17:57:35 -05001012 * :data:`stat.UF_NODUMP`
1013 * :data:`stat.UF_IMMUTABLE`
1014 * :data:`stat.UF_APPEND`
1015 * :data:`stat.UF_OPAQUE`
1016 * :data:`stat.UF_NOUNLINK`
Ned Deily43e10542011-06-27 23:41:53 -07001017 * :data:`stat.UF_COMPRESSED`
1018 * :data:`stat.UF_HIDDEN`
R David Murrayefd8bab2011-03-10 17:57:35 -05001019 * :data:`stat.SF_ARCHIVED`
1020 * :data:`stat.SF_IMMUTABLE`
1021 * :data:`stat.SF_APPEND`
1022 * :data:`stat.SF_NOUNLINK`
1023 * :data:`stat.SF_SNAPSHOT`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001024
Georg Brandl9af94982008-09-13 17:41:16 +00001025 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001026
1027 .. versionadded:: 2.6
1028
1029
1030.. function:: chroot(path)
1031
1032 Change the root directory of the current process to *path*. Availability:
Georg Brandl9af94982008-09-13 17:41:16 +00001033 Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001034
1035 .. versionadded:: 2.2
1036
1037
1038.. function:: chmod(path, mode)
1039
1040 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Georg Brandlf725b952008-01-05 19:44:22 +00001041 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl8ec7f652007-08-15 14:28:01 +00001042 combinations of them:
1043
1044
R. David Murrayfbba7cd2009-07-02 18:19:20 +00001045 * :data:`stat.S_ISUID`
1046 * :data:`stat.S_ISGID`
1047 * :data:`stat.S_ENFMT`
1048 * :data:`stat.S_ISVTX`
1049 * :data:`stat.S_IREAD`
1050 * :data:`stat.S_IWRITE`
1051 * :data:`stat.S_IEXEC`
1052 * :data:`stat.S_IRWXU`
1053 * :data:`stat.S_IRUSR`
1054 * :data:`stat.S_IWUSR`
1055 * :data:`stat.S_IXUSR`
1056 * :data:`stat.S_IRWXG`
1057 * :data:`stat.S_IRGRP`
1058 * :data:`stat.S_IWGRP`
1059 * :data:`stat.S_IXGRP`
1060 * :data:`stat.S_IRWXO`
1061 * :data:`stat.S_IROTH`
1062 * :data:`stat.S_IWOTH`
1063 * :data:`stat.S_IXOTH`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001064
Georg Brandl9af94982008-09-13 17:41:16 +00001065 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001066
1067 .. note::
1068
1069 Although Windows supports :func:`chmod`, you can only set the file's read-only
1070 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
1071 constants or a corresponding integer value). All other bits are
1072 ignored.
1073
1074
1075.. function:: chown(path, uid, gid)
1076
1077 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
Benjamin Peterson328e3772010-05-06 22:49:28 +00001078 one of the ids unchanged, set it to -1.
1079
1080 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001081
1082
1083.. function:: lchflags(path, flags)
1084
1085 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
Benjamin Peterson328e3772010-05-06 22:49:28 +00001086 follow symbolic links.
1087
1088 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001089
1090 .. versionadded:: 2.6
1091
1092
Georg Brandl81ddc1a2007-11-30 22:04:45 +00001093.. function:: lchmod(path, mode)
1094
1095 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
1096 affects the symlink rather than the target. See the docs for :func:`chmod`
Benjamin Peterson328e3772010-05-06 22:49:28 +00001097 for possible values of *mode*.
1098
1099 Availability: Unix.
Georg Brandl81ddc1a2007-11-30 22:04:45 +00001100
1101 .. versionadded:: 2.6
1102
1103
Georg Brandl8ec7f652007-08-15 14:28:01 +00001104.. function:: lchown(path, uid, gid)
1105
Georg Brandlf725b952008-01-05 19:44:22 +00001106 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Benjamin Peterson328e3772010-05-06 22:49:28 +00001107 function will not follow symbolic links.
1108
1109 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001110
1111 .. versionadded:: 2.3
1112
1113
Benjamin Peterson0e928582009-03-28 19:16:10 +00001114.. function:: link(source, link_name)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001115
Benjamin Peterson328e3772010-05-06 22:49:28 +00001116 Create a hard link pointing to *source* named *link_name*.
1117
1118 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001119
1120
1121.. function:: listdir(path)
1122
Georg Brandl62342912008-11-24 19:56:47 +00001123 Return a list containing the names of the entries in the directory given by
1124 *path*. The list is in arbitrary order. It does not include the special
1125 entries ``'.'`` and ``'..'`` even if they are present in the
Benjamin Peterson328e3772010-05-06 22:49:28 +00001126 directory.
1127
1128 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001129
1130 .. versionchanged:: 2.3
1131 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
Georg Brandld933cc22009-05-16 11:21:29 +00001132 a list of Unicode objects. Undecodable filenames will still be returned as
1133 string objects.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001134
1135
1136.. function:: lstat(path)
1137
Georg Brandlba516cb2011-02-12 07:32:17 +00001138 Perform the equivalent of an :cfunc:`lstat` system call on the given path.
R. David Murray561b96f2011-02-11 17:25:54 +00001139 Similar to :func:`~os.stat`, but does not follow symbolic links. On
1140 platforms that do not support symbolic links, this is an alias for
1141 :func:`~os.stat`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001142
1143
1144.. function:: mkfifo(path[, mode])
1145
1146 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
1147 *mode* is ``0666`` (octal). The current umask value is first masked out from
Benjamin Peterson328e3772010-05-06 22:49:28 +00001148 the mode.
1149
1150 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001151
1152 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
1153 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
1154 rendezvous between "client" and "server" type processes: the server opens the
1155 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
1156 doesn't open the FIFO --- it just creates the rendezvous point.
1157
1158
1159.. function:: mknod(filename[, mode=0600, device])
1160
1161 Create a filesystem node (file, device special file or named pipe) named
1162 *filename*. *mode* specifies both the permissions to use and the type of node to
1163 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
1164 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
1165 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
1166 For ``stat.S_IFCHR`` and
1167 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
1168 :func:`os.makedev`), otherwise it is ignored.
1169
1170 .. versionadded:: 2.3
1171
1172
1173.. function:: major(device)
1174
Georg Brandlf725b952008-01-05 19:44:22 +00001175 Extract the device major number from a raw device number (usually the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001176 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
1177
1178 .. versionadded:: 2.3
1179
1180
1181.. function:: minor(device)
1182
Georg Brandlf725b952008-01-05 19:44:22 +00001183 Extract the device minor number from a raw device number (usually the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001184 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
1185
1186 .. versionadded:: 2.3
1187
1188
1189.. function:: makedev(major, minor)
1190
Georg Brandlf725b952008-01-05 19:44:22 +00001191 Compose a raw device number from the major and minor device numbers.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001192
1193 .. versionadded:: 2.3
1194
1195
1196.. function:: mkdir(path[, mode])
1197
1198 Create a directory named *path* with numeric mode *mode*. The default *mode* is
1199 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
Georg Brandlab776ce2010-06-12 06:28:58 +00001200 current umask value is first masked out. If the directory already exists,
1201 :exc:`OSError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001202
Mark Summerfieldac3d4292007-11-02 08:24:59 +00001203 It is also possible to create temporary directories; see the
1204 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1205
Benjamin Peterson328e3772010-05-06 22:49:28 +00001206 Availability: Unix, Windows.
1207
Georg Brandl8ec7f652007-08-15 14:28:01 +00001208
1209.. function:: makedirs(path[, mode])
1210
1211 .. index::
1212 single: directory; creating
1213 single: UNC paths; and os.makedirs()
1214
1215 Recursive directory creation function. Like :func:`mkdir`, but makes all
Éric Araujo4c8d6b62010-11-30 17:53:45 +00001216 intermediate-level directories needed to contain the leaf directory. Raises an
Georg Brandl8ec7f652007-08-15 14:28:01 +00001217 :exc:`error` exception if the leaf directory already exists or cannot be
1218 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
1219 ignored. Where it is used, the current umask value is first masked out.
1220
1221 .. note::
1222
1223 :func:`makedirs` will become confused if the path elements to create include
Georg Brandlf725b952008-01-05 19:44:22 +00001224 :data:`os.pardir`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001225
1226 .. versionadded:: 1.5.2
1227
1228 .. versionchanged:: 2.3
1229 This function now handles UNC paths correctly.
1230
1231
1232.. function:: pathconf(path, name)
1233
1234 Return system configuration information relevant to a named file. *name*
1235 specifies the configuration value to retrieve; it may be a string which is the
1236 name of a defined system value; these names are specified in a number of
1237 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1238 additional names as well. The names known to the host operating system are
1239 given in the ``pathconf_names`` dictionary. For configuration variables not
1240 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001241
1242 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1243 specific value for *name* is not supported by the host system, even if it is
1244 included in ``pathconf_names``, an :exc:`OSError` is raised with
1245 :const:`errno.EINVAL` for the error number.
1246
Benjamin Peterson328e3772010-05-06 22:49:28 +00001247 Availability: Unix.
1248
Georg Brandl8ec7f652007-08-15 14:28:01 +00001249
1250.. data:: pathconf_names
1251
1252 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1253 the integer values defined for those names by the host operating system. This
1254 can be used to determine the set of names known to the system. Availability:
Georg Brandl9af94982008-09-13 17:41:16 +00001255 Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001256
1257
1258.. function:: readlink(path)
1259
1260 Return a string representing the path to which the symbolic link points. The
1261 result may be either an absolute or relative pathname; if it is relative, it may
1262 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1263 result)``.
1264
1265 .. versionchanged:: 2.6
1266 If the *path* is a Unicode object the result will also be a Unicode object.
1267
Georg Brandl9af94982008-09-13 17:41:16 +00001268 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001269
1270
1271.. function:: remove(path)
1272
Georg Brandl75439972009-08-24 17:24:27 +00001273 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
1274 raised; see :func:`rmdir` below to remove a directory. This is identical to
1275 the :func:`unlink` function documented below. On Windows, attempting to
1276 remove a file that is in use causes an exception to be raised; on Unix, the
1277 directory entry is removed but the storage allocated to the file is not made
Benjamin Peterson328e3772010-05-06 22:49:28 +00001278 available until the original file is no longer in use.
1279
1280 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001281
1282
1283.. function:: removedirs(path)
1284
1285 .. index:: single: directory; deleting
1286
Georg Brandlf725b952008-01-05 19:44:22 +00001287 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001288 leaf directory is successfully removed, :func:`removedirs` tries to
1289 successively remove every parent directory mentioned in *path* until an error
1290 is raised (which is ignored, because it generally means that a parent directory
1291 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1292 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1293 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1294 successfully removed.
1295
1296 .. versionadded:: 1.5.2
1297
1298
1299.. function:: rename(src, dst)
1300
1301 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1302 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Georg Brandlf725b952008-01-05 19:44:22 +00001303 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl8ec7f652007-08-15 14:28:01 +00001304 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1305 the renaming will be an atomic operation (this is a POSIX requirement). On
1306 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1307 file; there may be no way to implement an atomic rename when *dst* names an
Benjamin Peterson328e3772010-05-06 22:49:28 +00001308 existing file.
1309
1310 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001311
1312
1313.. function:: renames(old, new)
1314
1315 Recursive directory or file renaming function. Works like :func:`rename`, except
1316 creation of any intermediate directories needed to make the new pathname good is
1317 attempted first. After the rename, directories corresponding to rightmost path
1318 segments of the old name will be pruned away using :func:`removedirs`.
1319
1320 .. versionadded:: 1.5.2
1321
1322 .. note::
1323
1324 This function can fail with the new directory structure made if you lack
1325 permissions needed to remove the leaf directory or file.
1326
1327
1328.. function:: rmdir(path)
1329
Georg Brandl1b2695a2009-08-24 17:48:40 +00001330 Remove (delete) the directory *path*. Only works when the directory is
1331 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
Benjamin Peterson328e3772010-05-06 22:49:28 +00001332 directory trees, :func:`shutil.rmtree` can be used.
1333
1334 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001335
1336
1337.. function:: stat(path)
1338
Georg Brandlba516cb2011-02-12 07:32:17 +00001339 Perform the equivalent of a :cfunc:`stat` system call on the given path.
R. David Murray561b96f2011-02-11 17:25:54 +00001340 (This function follows symlinks; to stat a symlink use :func:`lstat`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001341
R. David Murray561b96f2011-02-11 17:25:54 +00001342 The return value is an object whose attributes correspond to the members
Georg Brandlba516cb2011-02-12 07:32:17 +00001343 of the :ctype:`stat` structure, namely:
R. David Murray561b96f2011-02-11 17:25:54 +00001344
1345 * :attr:`st_mode` - protection bits,
1346 * :attr:`st_ino` - inode number,
1347 * :attr:`st_dev` - device,
1348 * :attr:`st_nlink` - number of hard links,
1349 * :attr:`st_uid` - user id of owner,
1350 * :attr:`st_gid` - group id of owner,
1351 * :attr:`st_size` - size of file, in bytes,
1352 * :attr:`st_atime` - time of most recent access,
1353 * :attr:`st_mtime` - time of most recent content modification,
1354 * :attr:`st_ctime` - platform dependent; time of most recent metadata change on
1355 Unix, or the time of creation on Windows)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001356
1357 .. versionchanged:: 2.3
Georg Brandlf725b952008-01-05 19:44:22 +00001358 If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
Georg Brandl8ec7f652007-08-15 14:28:01 +00001359 seconds. Fractions of a second may be reported if the system supports that. On
1360 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1361 discussion.
1362
1363 On some Unix systems (such as Linux), the following attributes may also be
R. David Murray561b96f2011-02-11 17:25:54 +00001364 available:
1365
1366 * :attr:`st_blocks` - number of blocks allocated for file
1367 * :attr:`st_blksize` - filesystem blocksize
1368 * :attr:`st_rdev` - type of device if an inode device
1369 * :attr:`st_flags` - user defined flags for file
Georg Brandl8ec7f652007-08-15 14:28:01 +00001370
1371 On other Unix systems (such as FreeBSD), the following attributes may be
R. David Murray561b96f2011-02-11 17:25:54 +00001372 available (but may be only filled out if root tries to use them):
1373
1374 * :attr:`st_gen` - file generation number
1375 * :attr:`st_birthtime` - time of file creation
Georg Brandl8ec7f652007-08-15 14:28:01 +00001376
1377 On Mac OS systems, the following attributes may also be available:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001378
R. David Murray561b96f2011-02-11 17:25:54 +00001379 * :attr:`st_rsize`
1380 * :attr:`st_creator`
1381 * :attr:`st_type`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001382
R. David Murray561b96f2011-02-11 17:25:54 +00001383 On RISCOS systems, the following attributes are also available:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001384
R. David Murray561b96f2011-02-11 17:25:54 +00001385 * :attr:`st_ftype` (file type)
1386 * :attr:`st_attrs` (attributes)
1387 * :attr:`st_obtype` (object type).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001388
1389 .. note::
1390
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001391 The exact meaning and resolution of the :attr:`st_atime`,
1392 :attr:`st_mtime`, and :attr:`st_ctime` attributes depend on the operating
1393 system and the file system. For example, on Windows systems using the FAT
1394 or FAT32 file systems, :attr:`st_mtime` has 2-second resolution, and
1395 :attr:`st_atime` has only 1-day resolution. See your operating system
1396 documentation for details.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001397
R. David Murray561b96f2011-02-11 17:25:54 +00001398 For backward compatibility, the return value of :func:`~os.stat` is also accessible
1399 as a tuple of at least 10 integers giving the most important (and portable)
1400 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1401 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1402 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1403 :attr:`st_ctime`. More items may be added at the end by some implementations.
1404
1405 .. index:: module: stat
1406
1407 The standard module :mod:`stat` defines functions and constants that are useful
1408 for extracting information from a :ctype:`stat` structure. (On Windows, some
1409 items are filled with dummy values.)
1410
1411 Example::
1412
1413 >>> import os
1414 >>> statinfo = os.stat('somefile.txt')
1415 >>> statinfo
1416 (33188, 422511, 769, 1, 1032, 100, 926, 1105022698,1105022732, 1105022732)
1417 >>> statinfo.st_size
1418 926
1419
Georg Brandl9af94982008-09-13 17:41:16 +00001420 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001421
1422 .. versionchanged:: 2.2
1423 Added access to values as attributes of the returned object.
1424
1425 .. versionchanged:: 2.5
Georg Brandlf725b952008-01-05 19:44:22 +00001426 Added :attr:`st_gen` and :attr:`st_birthtime`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001427
1428
1429.. function:: stat_float_times([newvalue])
1430
1431 Determine whether :class:`stat_result` represents time stamps as float objects.
R. David Murray561b96f2011-02-11 17:25:54 +00001432 If *newvalue* is ``True``, future calls to :func:`~os.stat` return floats, if it is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001433 ``False``, future calls return ints. If *newvalue* is omitted, return the
1434 current setting.
1435
1436 For compatibility with older Python versions, accessing :class:`stat_result` as
1437 a tuple always returns integers.
1438
1439 .. versionchanged:: 2.5
1440 Python now returns float values by default. Applications which do not work
1441 correctly with floating point time stamps can use this function to restore the
1442 old behaviour.
1443
1444 The resolution of the timestamps (that is the smallest possible fraction)
1445 depends on the system. Some systems only support second resolution; on these
1446 systems, the fraction will always be zero.
1447
1448 It is recommended that this setting is only changed at program startup time in
1449 the *__main__* module; libraries should never change this setting. If an
1450 application uses a library that works incorrectly if floating point time stamps
1451 are processed, this application should turn the feature off until the library
1452 has been corrected.
1453
1454
1455.. function:: statvfs(path)
1456
1457 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1458 an object whose attributes describe the filesystem on the given path, and
1459 correspond to the members of the :ctype:`statvfs` structure, namely:
1460 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1461 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
Benjamin Peterson328e3772010-05-06 22:49:28 +00001462 :attr:`f_flag`, :attr:`f_namemax`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001463
1464 .. index:: module: statvfs
1465
1466 For backward compatibility, the return value is also accessible as a tuple whose
1467 values correspond to the attributes, in the order given above. The standard
1468 module :mod:`statvfs` defines constants that are useful for extracting
1469 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1470 this remains useful when writing code that needs to work with versions of Python
1471 that don't support accessing the fields as attributes.
1472
Benjamin Peterson328e3772010-05-06 22:49:28 +00001473 Availability: Unix.
1474
Georg Brandl8ec7f652007-08-15 14:28:01 +00001475 .. versionchanged:: 2.2
1476 Added access to values as attributes of the returned object.
1477
1478
Benjamin Peterson0e928582009-03-28 19:16:10 +00001479.. function:: symlink(source, link_name)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001480
Benjamin Peterson328e3772010-05-06 22:49:28 +00001481 Create a symbolic link pointing to *source* named *link_name*.
1482
1483 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001484
1485
1486.. function:: tempnam([dir[, prefix]])
1487
1488 Return a unique path name that is reasonable for creating a temporary file.
1489 This will be an absolute path that names a potential directory entry in the
1490 directory *dir* or a common location for temporary files if *dir* is omitted or
1491 ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
1492 to the filename. Applications are responsible for properly creating and
1493 managing files created using paths returned by :func:`tempnam`; no automatic
1494 cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
Georg Brandlf725b952008-01-05 19:44:22 +00001495 overrides *dir*, while on Windows :envvar:`TMP` is used. The specific
Georg Brandl8ec7f652007-08-15 14:28:01 +00001496 behavior of this function depends on the C library implementation; some aspects
1497 are underspecified in system documentation.
1498
1499 .. warning::
1500
1501 Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1502 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1503
Georg Brandl9af94982008-09-13 17:41:16 +00001504 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001505
1506
1507.. function:: tmpnam()
1508
1509 Return a unique path name that is reasonable for creating a temporary file.
1510 This will be an absolute path that names a potential directory entry in a common
1511 location for temporary files. Applications are responsible for properly
1512 creating and managing files created using paths returned by :func:`tmpnam`; no
1513 automatic cleanup is provided.
1514
1515 .. warning::
1516
1517 Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1518 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1519
1520 Availability: Unix, Windows. This function probably shouldn't be used on
1521 Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1522 name in the root directory of the current drive, and that's generally a poor
1523 location for a temp file (depending on privileges, you may not even be able to
1524 open a file using this name).
1525
1526
1527.. data:: TMP_MAX
1528
1529 The maximum number of unique names that :func:`tmpnam` will generate before
1530 reusing names.
1531
1532
1533.. function:: unlink(path)
1534
Georg Brandl75439972009-08-24 17:24:27 +00001535 Remove (delete) the file *path*. This is the same function as
1536 :func:`remove`; the :func:`unlink` name is its traditional Unix
Benjamin Peterson328e3772010-05-06 22:49:28 +00001537 name.
1538
1539 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001540
1541
1542.. function:: utime(path, times)
1543
Benjamin Peterson5b02ef32008-08-16 03:13:07 +00001544 Set the access and modified times of the file specified by *path*. If *times*
1545 is ``None``, then the file's access and modified times are set to the current
1546 time. (The effect is similar to running the Unix program :program:`touch` on
1547 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1548 ``(atime, mtime)`` which is used to set the access and modified times,
1549 respectively. Whether a directory can be given for *path* depends on whether
1550 the operating system implements directories as files (for example, Windows
1551 does not). Note that the exact times you set here may not be returned by a
R. David Murray561b96f2011-02-11 17:25:54 +00001552 subsequent :func:`~os.stat` call, depending on the resolution with which your
1553 operating system records access and modification times; see :func:`~os.stat`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001554
1555 .. versionchanged:: 2.0
1556 Added support for ``None`` for *times*.
1557
Georg Brandl9af94982008-09-13 17:41:16 +00001558 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001559
1560
1561.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1562
1563 .. index::
1564 single: directory; walking
1565 single: directory; traversal
1566
Georg Brandlf725b952008-01-05 19:44:22 +00001567 Generate the file names in a directory tree by walking the tree
1568 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl8ec7f652007-08-15 14:28:01 +00001569 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1570 filenames)``.
1571
1572 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1573 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1574 *filenames* is a list of the names of the non-directory files in *dirpath*.
1575 Note that the names in the lists contain no path components. To get a full path
1576 (which begins with *top*) to a file or directory in *dirpath*, do
1577 ``os.path.join(dirpath, name)``.
1578
Georg Brandlf725b952008-01-05 19:44:22 +00001579 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001580 directory is generated before the triples for any of its subdirectories
Georg Brandlf725b952008-01-05 19:44:22 +00001581 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001582 directory is generated after the triples for all of its subdirectories
Georg Brandlf725b952008-01-05 19:44:22 +00001583 (directories are generated bottom-up).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001584
Georg Brandlf725b952008-01-05 19:44:22 +00001585 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl8ec7f652007-08-15 14:28:01 +00001586 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1587 recurse into the subdirectories whose names remain in *dirnames*; this can be
1588 used to prune the search, impose a specific order of visiting, or even to inform
1589 :func:`walk` about directories the caller creates or renames before it resumes
Georg Brandlf725b952008-01-05 19:44:22 +00001590 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001591 ineffective, because in bottom-up mode the directories in *dirnames* are
1592 generated before *dirpath* itself is generated.
1593
Georg Brandlf725b952008-01-05 19:44:22 +00001594 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl8ec7f652007-08-15 14:28:01 +00001595 argument *onerror* is specified, it should be a function; it will be called with
1596 one argument, an :exc:`OSError` instance. It can report the error to continue
1597 with the walk, or raise the exception to abort the walk. Note that the filename
1598 is available as the ``filename`` attribute of the exception object.
1599
1600 By default, :func:`walk` will not walk down into symbolic links that resolve to
Georg Brandlf725b952008-01-05 19:44:22 +00001601 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl8ec7f652007-08-15 14:28:01 +00001602 symlinks, on systems that support them.
1603
1604 .. versionadded:: 2.6
1605 The *followlinks* parameter.
1606
1607 .. note::
1608
Georg Brandlf725b952008-01-05 19:44:22 +00001609 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001610 link points to a parent directory of itself. :func:`walk` does not keep track of
1611 the directories it visited already.
1612
1613 .. note::
1614
1615 If you pass a relative pathname, don't change the current working directory
1616 between resumptions of :func:`walk`. :func:`walk` never changes the current
1617 directory, and assumes that its caller doesn't either.
1618
1619 This example displays the number of bytes taken by non-directory files in each
1620 directory under the starting directory, except that it doesn't look under any
1621 CVS subdirectory::
1622
1623 import os
1624 from os.path import join, getsize
1625 for root, dirs, files in os.walk('python/Lib/email'):
1626 print root, "consumes",
1627 print sum(getsize(join(root, name)) for name in files),
1628 print "bytes in", len(files), "non-directory files"
1629 if 'CVS' in dirs:
1630 dirs.remove('CVS') # don't visit CVS directories
1631
Georg Brandlf725b952008-01-05 19:44:22 +00001632 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001633 doesn't allow deleting a directory before the directory is empty::
1634
Georg Brandlf725b952008-01-05 19:44:22 +00001635 # Delete everything reachable from the directory named in "top",
Georg Brandl8ec7f652007-08-15 14:28:01 +00001636 # assuming there are no symbolic links.
1637 # CAUTION: This is dangerous! For example, if top == '/', it
1638 # could delete all your disk files.
1639 import os
1640 for root, dirs, files in os.walk(top, topdown=False):
1641 for name in files:
1642 os.remove(os.path.join(root, name))
1643 for name in dirs:
1644 os.rmdir(os.path.join(root, name))
1645
1646 .. versionadded:: 2.3
1647
1648
1649.. _os-process:
1650
1651Process Management
1652------------------
1653
1654These functions may be used to create and manage processes.
1655
1656The various :func:`exec\*` functions take a list of arguments for the new
1657program loaded into the process. In each case, the first of these arguments is
1658passed to the new program as its own name rather than as an argument a user may
1659have typed on a command line. For the C programmer, this is the ``argv[0]``
1660passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1661['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1662to be ignored.
1663
1664
1665.. function:: abort()
1666
1667 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1668 behavior is to produce a core dump; on Windows, the process immediately returns
1669 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1670 to register a handler for :const:`SIGABRT` will behave differently.
Benjamin Peterson328e3772010-05-06 22:49:28 +00001671
Georg Brandl9af94982008-09-13 17:41:16 +00001672 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001673
1674
1675.. function:: execl(path, arg0, arg1, ...)
1676 execle(path, arg0, arg1, ..., env)
1677 execlp(file, arg0, arg1, ...)
1678 execlpe(file, arg0, arg1, ..., env)
1679 execv(path, args)
1680 execve(path, args, env)
1681 execvp(file, args)
1682 execvpe(file, args, env)
1683
1684 These functions all execute a new program, replacing the current process; they
1685 do not return. On Unix, the new executable is loaded into the current process,
Georg Brandlf725b952008-01-05 19:44:22 +00001686 and will have the same process id as the caller. Errors will be reported as
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001687 :exc:`OSError` exceptions.
Andrew M. Kuchlingac771662008-09-28 00:15:27 +00001688
1689 The current process is replaced immediately. Open file objects and
1690 descriptors are not flushed, so if there may be data buffered
1691 on these open files, you should flush them using
1692 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
1693 :func:`exec\*` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001694
Georg Brandlf725b952008-01-05 19:44:22 +00001695 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1696 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl8ec7f652007-08-15 14:28:01 +00001697 to work with if the number of parameters is fixed when the code is written; the
1698 individual parameters simply become additional parameters to the :func:`execl\*`
Georg Brandlf725b952008-01-05 19:44:22 +00001699 functions. The "v" variants are good when the number of parameters is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001700 variable, with the arguments being passed in a list or tuple as the *args*
1701 parameter. In either case, the arguments to the child process should start with
1702 the name of the command being run, but this is not enforced.
1703
Georg Brandlf725b952008-01-05 19:44:22 +00001704 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001705 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1706 :envvar:`PATH` environment variable to locate the program *file*. When the
1707 environment is being replaced (using one of the :func:`exec\*e` variants,
1708 discussed in the next paragraph), the new environment is used as the source of
1709 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1710 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1711 locate the executable; *path* must contain an appropriate absolute or relative
1712 path.
1713
1714 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Georg Brandlf725b952008-01-05 19:44:22 +00001715 that these all end in "e"), the *env* parameter must be a mapping which is
Georg Brandlfb246c42008-04-19 16:58:28 +00001716 used to define the environment variables for the new process (these are used
1717 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001718 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001719 inherit the environment of the current process.
Andrew M. Kuchlingac771662008-09-28 00:15:27 +00001720
1721 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001722
1723
1724.. function:: _exit(n)
1725
Georg Brandlb8d0e362010-11-26 07:53:50 +00001726 Exit the process with status *n*, without calling cleanup handlers, flushing
Benjamin Peterson328e3772010-05-06 22:49:28 +00001727 stdio buffers, etc.
1728
1729 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001730
1731 .. note::
1732
Georg Brandlb8d0e362010-11-26 07:53:50 +00001733 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should
1734 normally only be used in the child process after a :func:`fork`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001735
Georg Brandlf725b952008-01-05 19:44:22 +00001736The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001737although they are not required. These are typically used for system programs
1738written in Python, such as a mail server's external command delivery program.
1739
1740.. note::
1741
1742 Some of these may not be available on all Unix platforms, since there is some
1743 variation. These constants are defined where they are defined by the underlying
1744 platform.
1745
1746
1747.. data:: EX_OK
1748
Benjamin Peterson328e3772010-05-06 22:49:28 +00001749 Exit code that means no error occurred.
1750
1751 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001752
1753 .. versionadded:: 2.3
1754
1755
1756.. data:: EX_USAGE
1757
1758 Exit code that means the command was used incorrectly, such as when the wrong
Benjamin Peterson328e3772010-05-06 22:49:28 +00001759 number of arguments are given.
1760
1761 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001762
1763 .. versionadded:: 2.3
1764
1765
1766.. data:: EX_DATAERR
1767
Benjamin Peterson328e3772010-05-06 22:49:28 +00001768 Exit code that means the input data was incorrect.
1769
1770 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001771
1772 .. versionadded:: 2.3
1773
1774
1775.. data:: EX_NOINPUT
1776
1777 Exit code that means an input file did not exist or was not readable.
Benjamin Peterson328e3772010-05-06 22:49:28 +00001778
Georg Brandl9af94982008-09-13 17:41:16 +00001779 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001780
1781 .. versionadded:: 2.3
1782
1783
1784.. data:: EX_NOUSER
1785
Benjamin Peterson328e3772010-05-06 22:49:28 +00001786 Exit code that means a specified user did not exist.
1787
1788 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001789
1790 .. versionadded:: 2.3
1791
1792
1793.. data:: EX_NOHOST
1794
Benjamin Peterson328e3772010-05-06 22:49:28 +00001795 Exit code that means a specified host did not exist.
1796
1797 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001798
1799 .. versionadded:: 2.3
1800
1801
1802.. data:: EX_UNAVAILABLE
1803
Benjamin Peterson328e3772010-05-06 22:49:28 +00001804 Exit code that means that a required service is unavailable.
1805
1806 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001807
1808 .. versionadded:: 2.3
1809
1810
1811.. data:: EX_SOFTWARE
1812
Benjamin Peterson328e3772010-05-06 22:49:28 +00001813 Exit code that means an internal software error was detected.
1814
1815 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001816
1817 .. versionadded:: 2.3
1818
1819
1820.. data:: EX_OSERR
1821
1822 Exit code that means an operating system error was detected, such as the
Benjamin Peterson328e3772010-05-06 22:49:28 +00001823 inability to fork or create a pipe.
1824
1825 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001826
1827 .. versionadded:: 2.3
1828
1829
1830.. data:: EX_OSFILE
1831
1832 Exit code that means some system file did not exist, could not be opened, or had
Benjamin Peterson328e3772010-05-06 22:49:28 +00001833 some other kind of error.
1834
1835 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001836
1837 .. versionadded:: 2.3
1838
1839
1840.. data:: EX_CANTCREAT
1841
1842 Exit code that means a user specified output file could not be created.
Benjamin Peterson328e3772010-05-06 22:49:28 +00001843
Georg Brandl9af94982008-09-13 17:41:16 +00001844 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001845
1846 .. versionadded:: 2.3
1847
1848
1849.. data:: EX_IOERR
1850
1851 Exit code that means that an error occurred while doing I/O on some file.
Benjamin Peterson328e3772010-05-06 22:49:28 +00001852
Georg Brandl9af94982008-09-13 17:41:16 +00001853 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001854
1855 .. versionadded:: 2.3
1856
1857
1858.. data:: EX_TEMPFAIL
1859
1860 Exit code that means a temporary failure occurred. This indicates something
1861 that may not really be an error, such as a network connection that couldn't be
Benjamin Peterson328e3772010-05-06 22:49:28 +00001862 made during a retryable operation.
1863
1864 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001865
1866 .. versionadded:: 2.3
1867
1868
1869.. data:: EX_PROTOCOL
1870
1871 Exit code that means that a protocol exchange was illegal, invalid, or not
Benjamin Peterson328e3772010-05-06 22:49:28 +00001872 understood.
1873
1874 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001875
1876 .. versionadded:: 2.3
1877
1878
1879.. data:: EX_NOPERM
1880
1881 Exit code that means that there were insufficient permissions to perform the
Benjamin Peterson328e3772010-05-06 22:49:28 +00001882 operation (but not intended for file system problems).
1883
1884 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001885
1886 .. versionadded:: 2.3
1887
1888
1889.. data:: EX_CONFIG
1890
1891 Exit code that means that some kind of configuration error occurred.
Benjamin Peterson328e3772010-05-06 22:49:28 +00001892
Georg Brandl9af94982008-09-13 17:41:16 +00001893 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001894
1895 .. versionadded:: 2.3
1896
1897
1898.. data:: EX_NOTFOUND
1899
Benjamin Peterson328e3772010-05-06 22:49:28 +00001900 Exit code that means something like "an entry was not found".
1901
1902 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001903
1904 .. versionadded:: 2.3
1905
1906
1907.. function:: fork()
1908
Georg Brandlf725b952008-01-05 19:44:22 +00001909 Fork a child process. Return ``0`` in the child and the child's process id in the
Skip Montanaro75e51682008-03-15 02:32:49 +00001910 parent. If an error occurs :exc:`OSError` is raised.
Gregory P. Smith08067492008-09-30 20:41:13 +00001911
1912 Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
1913 known issues when using fork() from a thread.
1914
Georg Brandl9af94982008-09-13 17:41:16 +00001915 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001916
1917
1918.. function:: forkpty()
1919
1920 Fork a child process, using a new pseudo-terminal as the child's controlling
1921 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1922 new child's process id in the parent, and *fd* is the file descriptor of the
1923 master end of the pseudo-terminal. For a more portable approach, use the
Skip Montanaro75e51682008-03-15 02:32:49 +00001924 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
Benjamin Peterson328e3772010-05-06 22:49:28 +00001925
Georg Brandl9af94982008-09-13 17:41:16 +00001926 Availability: some flavors of Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001927
1928
1929.. function:: kill(pid, sig)
1930
1931 .. index::
1932 single: process; killing
1933 single: process; signalling
1934
1935 Send signal *sig* to the process *pid*. Constants for the specific signals
1936 available on the host platform are defined in the :mod:`signal` module.
Brian Curtine5aa8862010-04-02 23:26:06 +00001937
1938 Windows: The :data:`signal.CTRL_C_EVENT` and
1939 :data:`signal.CTRL_BREAK_EVENT` signals are special signals which can
1940 only be sent to console processes which share a common console window,
1941 e.g., some subprocesses. Any other value for *sig* will cause the process
1942 to be unconditionally killed by the TerminateProcess API, and the exit code
1943 will be set to *sig*. The Windows version of :func:`kill` additionally takes
1944 process handles to be killed.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001945
Brian Curtin1f8dd362010-04-20 15:23:18 +00001946 .. versionadded:: 2.7 Windows support
1947
Georg Brandl8ec7f652007-08-15 14:28:01 +00001948
1949.. function:: killpg(pgid, sig)
1950
1951 .. index::
1952 single: process; killing
1953 single: process; signalling
1954
Benjamin Peterson328e3772010-05-06 22:49:28 +00001955 Send the signal *sig* to the process group *pgid*.
1956
1957 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001958
1959 .. versionadded:: 2.3
1960
1961
1962.. function:: nice(increment)
1963
1964 Add *increment* to the process's "niceness". Return the new niceness.
Benjamin Peterson328e3772010-05-06 22:49:28 +00001965
Georg Brandl9af94982008-09-13 17:41:16 +00001966 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001967
1968
1969.. function:: plock(op)
1970
1971 Lock program segments into memory. The value of *op* (defined in
Benjamin Peterson328e3772010-05-06 22:49:28 +00001972 ``<sys/lock.h>``) determines which segments are locked.
1973
1974 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001975
1976
1977.. function:: popen(...)
1978 popen2(...)
1979 popen3(...)
1980 popen4(...)
1981 :noindex:
1982
1983 Run child processes, returning opened pipes for communications. These functions
1984 are described in section :ref:`os-newstreams`.
1985
1986
1987.. function:: spawnl(mode, path, ...)
1988 spawnle(mode, path, ..., env)
1989 spawnlp(mode, file, ...)
1990 spawnlpe(mode, file, ..., env)
1991 spawnv(mode, path, args)
1992 spawnve(mode, path, args, env)
1993 spawnvp(mode, file, args)
1994 spawnvpe(mode, file, args, env)
1995
1996 Execute the program *path* in a new process.
1997
1998 (Note that the :mod:`subprocess` module provides more powerful facilities for
1999 spawning new processes and retrieving their results; using that module is
R. David Murrayccb9d4b2009-06-09 00:44:22 +00002000 preferable to using these functions. Check especially the
2001 :ref:`subprocess-replacements` section.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002002
Georg Brandlf725b952008-01-05 19:44:22 +00002003 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl8ec7f652007-08-15 14:28:01 +00002004 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
2005 exits normally, or ``-signal``, where *signal* is the signal that killed the
Georg Brandlf725b952008-01-05 19:44:22 +00002006 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl8ec7f652007-08-15 14:28:01 +00002007 be used with the :func:`waitpid` function.
2008
Georg Brandlf725b952008-01-05 19:44:22 +00002009 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
2010 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl8ec7f652007-08-15 14:28:01 +00002011 to work with if the number of parameters is fixed when the code is written; the
2012 individual parameters simply become additional parameters to the
Georg Brandlf725b952008-01-05 19:44:22 +00002013 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl8ec7f652007-08-15 14:28:01 +00002014 parameters is variable, with the arguments being passed in a list or tuple as
2015 the *args* parameter. In either case, the arguments to the child process must
2016 start with the name of the command being run.
2017
Georg Brandlf725b952008-01-05 19:44:22 +00002018 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00002019 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
2020 :envvar:`PATH` environment variable to locate the program *file*. When the
2021 environment is being replaced (using one of the :func:`spawn\*e` variants,
2022 discussed in the next paragraph), the new environment is used as the source of
2023 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
2024 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
2025 :envvar:`PATH` variable to locate the executable; *path* must contain an
2026 appropriate absolute or relative path.
2027
2028 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Georg Brandlf725b952008-01-05 19:44:22 +00002029 (note that these all end in "e"), the *env* parameter must be a mapping
Georg Brandlfb246c42008-04-19 16:58:28 +00002030 which is used to define the environment variables for the new process (they are
2031 used instead of the current process' environment); the functions
Georg Brandl8ec7f652007-08-15 14:28:01 +00002032 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
Georg Brandl22717df2009-03-31 18:26:55 +00002033 the new process to inherit the environment of the current process. Note that
2034 keys and values in the *env* dictionary must be strings; invalid keys or
2035 values will cause the function to fail, with a return value of ``127``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002036
2037 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
2038 equivalent::
2039
2040 import os
2041 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
2042
2043 L = ['cp', 'index.html', '/dev/null']
2044 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
2045
2046 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
2047 and :func:`spawnvpe` are not available on Windows.
2048
2049 .. versionadded:: 1.6
2050
2051
2052.. data:: P_NOWAIT
2053 P_NOWAITO
2054
2055 Possible values for the *mode* parameter to the :func:`spawn\*` family of
2056 functions. If either of these values is given, the :func:`spawn\*` functions
Georg Brandlf725b952008-01-05 19:44:22 +00002057 will return as soon as the new process has been created, with the process id as
Benjamin Peterson328e3772010-05-06 22:49:28 +00002058 the return value.
2059
2060 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002061
2062 .. versionadded:: 1.6
2063
2064
2065.. data:: P_WAIT
2066
2067 Possible value for the *mode* parameter to the :func:`spawn\*` family of
2068 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
2069 return until the new process has run to completion and will return the exit code
2070 of the process the run is successful, or ``-signal`` if a signal kills the
Benjamin Peterson328e3772010-05-06 22:49:28 +00002071 process.
2072
2073 Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002074
2075 .. versionadded:: 1.6
2076
2077
2078.. data:: P_DETACH
2079 P_OVERLAY
2080
2081 Possible values for the *mode* parameter to the :func:`spawn\*` family of
2082 functions. These are less portable than those listed above. :const:`P_DETACH`
2083 is similar to :const:`P_NOWAIT`, but the new process is detached from the
2084 console of the calling process. If :const:`P_OVERLAY` is used, the current
2085 process will be replaced; the :func:`spawn\*` function will not return.
Benjamin Peterson328e3772010-05-06 22:49:28 +00002086
Georg Brandl8ec7f652007-08-15 14:28:01 +00002087 Availability: Windows.
2088
2089 .. versionadded:: 1.6
2090
2091
2092.. function:: startfile(path[, operation])
2093
2094 Start a file with its associated application.
2095
2096 When *operation* is not specified or ``'open'``, this acts like double-clicking
2097 the file in Windows Explorer, or giving the file name as an argument to the
2098 :program:`start` command from the interactive command shell: the file is opened
2099 with whatever application (if any) its extension is associated.
2100
2101 When another *operation* is given, it must be a "command verb" that specifies
2102 what should be done with the file. Common verbs documented by Microsoft are
2103 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
2104 ``'find'`` (to be used on directories).
2105
2106 :func:`startfile` returns as soon as the associated application is launched.
2107 There is no option to wait for the application to close, and no way to retrieve
2108 the application's exit status. The *path* parameter is relative to the current
2109 directory. If you want to use an absolute path, make sure the first character
2110 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
2111 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
Benjamin Peterson328e3772010-05-06 22:49:28 +00002112 the path is properly encoded for Win32.
2113
2114 Availability: Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002115
2116 .. versionadded:: 2.0
2117
2118 .. versionadded:: 2.5
2119 The *operation* parameter.
2120
2121
2122.. function:: system(command)
2123
2124 Execute the command (a string) in a subshell. This is implemented by calling
Georg Brandl647e9d22009-10-14 15:57:46 +00002125 the Standard C function :cfunc:`system`, and has the same limitations.
Georg Brandl11abfe62009-10-18 07:58:12 +00002126 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the
Georg Brandl647e9d22009-10-14 15:57:46 +00002127 executed command.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002128
2129 On Unix, the return value is the exit status of the process encoded in the
2130 format specified for :func:`wait`. Note that POSIX does not specify the meaning
2131 of the return value of the C :cfunc:`system` function, so the return value of
2132 the Python function is system-dependent.
2133
2134 On Windows, the return value is that returned by the system shell after running
2135 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
2136 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
2137 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
2138 the command run; on systems using a non-native shell, consult your shell
2139 documentation.
2140
Georg Brandl8ec7f652007-08-15 14:28:01 +00002141 The :mod:`subprocess` module provides more powerful facilities for spawning new
2142 processes and retrieving their results; using that module is preferable to using
Andrew M. Kuchlingfdf94c52010-07-26 13:42:35 +00002143 this function. See the
2144 :ref:`subprocess-replacements` section in the :mod:`subprocess` documentation
2145 for some helpful recipes.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002146
Benjamin Peterson328e3772010-05-06 22:49:28 +00002147 Availability: Unix, Windows.
2148
Georg Brandl8ec7f652007-08-15 14:28:01 +00002149
2150.. function:: times()
2151
Benjamin Peterson328e3772010-05-06 22:49:28 +00002152 Return a 5-tuple of floating point numbers indicating accumulated (processor
2153 or other) times, in seconds. The items are: user time, system time,
2154 children's user time, children's system time, and elapsed real time since a
2155 fixed point in the past, in that order. See the Unix manual page
2156 :manpage:`times(2)` or the corresponding Windows Platform API documentation.
2157 On Windows, only the first two items are filled, the others are zero.
2158
2159 Availability: Unix, Windows
Georg Brandl8ec7f652007-08-15 14:28:01 +00002160
2161
2162.. function:: wait()
2163
2164 Wait for completion of a child process, and return a tuple containing its pid
2165 and exit status indication: a 16-bit number, whose low byte is the signal number
2166 that killed the process, and whose high byte is the exit status (if the signal
2167 number is zero); the high bit of the low byte is set if a core file was
Benjamin Peterson328e3772010-05-06 22:49:28 +00002168 produced.
2169
2170 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002171
2172
2173.. function:: waitpid(pid, options)
2174
2175 The details of this function differ on Unix and Windows.
2176
2177 On Unix: Wait for completion of a child process given by process id *pid*, and
2178 return a tuple containing its process id and exit status indication (encoded as
2179 for :func:`wait`). The semantics of the call are affected by the value of the
2180 integer *options*, which should be ``0`` for normal operation.
2181
2182 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
2183 that specific process. If *pid* is ``0``, the request is for the status of any
2184 child in the process group of the current process. If *pid* is ``-1``, the
2185 request pertains to any child of the current process. If *pid* is less than
2186 ``-1``, status is requested for any process in the process group ``-pid`` (the
2187 absolute value of *pid*).
2188
Gregory P. Smith59de7f52008-08-15 23:14:00 +00002189 An :exc:`OSError` is raised with the value of errno when the syscall
2190 returns -1.
2191
Georg Brandl8ec7f652007-08-15 14:28:01 +00002192 On Windows: Wait for completion of a process given by process handle *pid*, and
2193 return a tuple containing *pid*, and its exit status shifted left by 8 bits
2194 (shifting makes cross-platform use of the function easier). A *pid* less than or
2195 equal to ``0`` has no special meaning on Windows, and raises an exception. The
2196 value of integer *options* has no effect. *pid* can refer to any process whose
2197 id is known, not necessarily a child process. The :func:`spawn` functions called
2198 with :const:`P_NOWAIT` return suitable process handles.
2199
2200
2201.. function:: wait3([options])
2202
2203 Similar to :func:`waitpid`, except no process id argument is given and a
2204 3-element tuple containing the child's process id, exit status indication, and
2205 resource usage information is returned. Refer to :mod:`resource`.\
2206 :func:`getrusage` for details on resource usage information. The option
2207 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
Benjamin Peterson328e3772010-05-06 22:49:28 +00002208
Georg Brandl8ec7f652007-08-15 14:28:01 +00002209 Availability: Unix.
2210
2211 .. versionadded:: 2.5
2212
2213
2214.. function:: wait4(pid, options)
2215
2216 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
2217 process id, exit status indication, and resource usage information is returned.
2218 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
2219 information. The arguments to :func:`wait4` are the same as those provided to
Benjamin Peterson328e3772010-05-06 22:49:28 +00002220 :func:`waitpid`.
2221
2222 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002223
2224 .. versionadded:: 2.5
2225
2226
2227.. data:: WNOHANG
2228
2229 The option for :func:`waitpid` to return immediately if no child process status
2230 is available immediately. The function returns ``(0, 0)`` in this case.
Benjamin Peterson328e3772010-05-06 22:49:28 +00002231
Georg Brandl9af94982008-09-13 17:41:16 +00002232 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002233
2234
2235.. data:: WCONTINUED
2236
2237 This option causes child processes to be reported if they have been continued
Benjamin Peterson328e3772010-05-06 22:49:28 +00002238 from a job control stop since their status was last reported.
2239
2240 Availability: Some Unix systems.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002241
2242 .. versionadded:: 2.3
2243
2244
2245.. data:: WUNTRACED
2246
2247 This option causes child processes to be reported if they have been stopped but
Benjamin Peterson328e3772010-05-06 22:49:28 +00002248 their current state has not been reported since they were stopped.
2249
2250 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002251
2252 .. versionadded:: 2.3
2253
2254The following functions take a process status code as returned by
2255:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
2256used to determine the disposition of a process.
2257
2258
2259.. function:: WCOREDUMP(status)
2260
Georg Brandlf725b952008-01-05 19:44:22 +00002261 Return ``True`` if a core dump was generated for the process, otherwise
Benjamin Peterson328e3772010-05-06 22:49:28 +00002262 return ``False``.
2263
2264 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002265
2266 .. versionadded:: 2.3
2267
2268
2269.. function:: WIFCONTINUED(status)
2270
Georg Brandlf725b952008-01-05 19:44:22 +00002271 Return ``True`` if the process has been continued from a job control stop,
Benjamin Peterson328e3772010-05-06 22:49:28 +00002272 otherwise return ``False``.
2273
2274 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002275
2276 .. versionadded:: 2.3
2277
2278
2279.. function:: WIFSTOPPED(status)
2280
Georg Brandlf725b952008-01-05 19:44:22 +00002281 Return ``True`` if the process has been stopped, otherwise return
Benjamin Peterson328e3772010-05-06 22:49:28 +00002282 ``False``.
2283
2284 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002285
2286
2287.. function:: WIFSIGNALED(status)
2288
Georg Brandlf725b952008-01-05 19:44:22 +00002289 Return ``True`` if the process exited due to a signal, otherwise return
Benjamin Peterson328e3772010-05-06 22:49:28 +00002290 ``False``.
2291
2292 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002293
2294
2295.. function:: WIFEXITED(status)
2296
Georg Brandlf725b952008-01-05 19:44:22 +00002297 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
Benjamin Peterson328e3772010-05-06 22:49:28 +00002298 otherwise return ``False``.
2299
2300 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002301
2302
2303.. function:: WEXITSTATUS(status)
2304
2305 If ``WIFEXITED(status)`` is true, return the integer parameter to the
2306 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
Benjamin Peterson328e3772010-05-06 22:49:28 +00002307
Georg Brandl9af94982008-09-13 17:41:16 +00002308 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002309
2310
2311.. function:: WSTOPSIG(status)
2312
Benjamin Peterson328e3772010-05-06 22:49:28 +00002313 Return the signal which caused the process to stop.
2314
2315 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002316
2317
2318.. function:: WTERMSIG(status)
2319
Benjamin Peterson328e3772010-05-06 22:49:28 +00002320 Return the signal which caused the process to exit.
2321
2322 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002323
2324
2325.. _os-path:
2326
2327Miscellaneous System Information
2328--------------------------------
2329
2330
2331.. function:: confstr(name)
2332
2333 Return string-valued system configuration values. *name* specifies the
2334 configuration value to retrieve; it may be a string which is the name of a
2335 defined system value; these names are specified in a number of standards (POSIX,
2336 Unix 95, Unix 98, and others). Some platforms define additional names as well.
2337 The names known to the host operating system are given as the keys of the
2338 ``confstr_names`` dictionary. For configuration variables not included in that
Benjamin Peterson328e3772010-05-06 22:49:28 +00002339 mapping, passing an integer for *name* is also accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002340
2341 If the configuration value specified by *name* isn't defined, ``None`` is
2342 returned.
2343
2344 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2345 specific value for *name* is not supported by the host system, even if it is
2346 included in ``confstr_names``, an :exc:`OSError` is raised with
2347 :const:`errno.EINVAL` for the error number.
2348
Benjamin Peterson328e3772010-05-06 22:49:28 +00002349 Availability: Unix
2350
Georg Brandl8ec7f652007-08-15 14:28:01 +00002351
2352.. data:: confstr_names
2353
2354 Dictionary mapping names accepted by :func:`confstr` to the integer values
2355 defined for those names by the host operating system. This can be used to
Benjamin Peterson328e3772010-05-06 22:49:28 +00002356 determine the set of names known to the system.
2357
2358 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002359
2360
2361.. function:: getloadavg()
2362
Georg Brandl57fe0f22008-01-12 10:53:29 +00002363 Return the number of processes in the system run queue averaged over the last
2364 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Benjamin Peterson328e3772010-05-06 22:49:28 +00002365 unobtainable.
2366
2367 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002368
2369 .. versionadded:: 2.3
2370
2371
2372.. function:: sysconf(name)
2373
2374 Return integer-valued system configuration values. If the configuration value
2375 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2376 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2377 provides information on the known names is given by ``sysconf_names``.
Benjamin Peterson328e3772010-05-06 22:49:28 +00002378
Georg Brandl9af94982008-09-13 17:41:16 +00002379 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002380
2381
2382.. data:: sysconf_names
2383
2384 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2385 defined for those names by the host operating system. This can be used to
Benjamin Peterson328e3772010-05-06 22:49:28 +00002386 determine the set of names known to the system.
2387
2388 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002389
Georg Brandlf725b952008-01-05 19:44:22 +00002390The following data values are used to support path manipulation operations. These
Georg Brandl8ec7f652007-08-15 14:28:01 +00002391are defined for all platforms.
2392
2393Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2394
2395
2396.. data:: curdir
2397
2398 The constant string used by the operating system to refer to the current
Georg Brandl9af94982008-09-13 17:41:16 +00002399 directory. This is ``'.'`` for Windows and POSIX. Also available via
2400 :mod:`os.path`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002401
2402
2403.. data:: pardir
2404
2405 The constant string used by the operating system to refer to the parent
Georg Brandl9af94982008-09-13 17:41:16 +00002406 directory. This is ``'..'`` for Windows and POSIX. Also available via
2407 :mod:`os.path`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002408
2409
2410.. data:: sep
2411
Georg Brandl9af94982008-09-13 17:41:16 +00002412 The character used by the operating system to separate pathname components.
2413 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
2414 is not sufficient to be able to parse or concatenate pathnames --- use
Georg Brandl8ec7f652007-08-15 14:28:01 +00002415 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2416 useful. Also available via :mod:`os.path`.
2417
2418
2419.. data:: altsep
2420
2421 An alternative character used by the operating system to separate pathname
2422 components, or ``None`` if only one separator character exists. This is set to
2423 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2424 :mod:`os.path`.
2425
2426
2427.. data:: extsep
2428
2429 The character which separates the base filename from the extension; for example,
2430 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2431
2432 .. versionadded:: 2.2
2433
2434
2435.. data:: pathsep
2436
2437 The character conventionally used by the operating system to separate search
2438 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2439 Windows. Also available via :mod:`os.path`.
2440
2441
2442.. data:: defpath
2443
2444 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
2445 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
2446
2447
2448.. data:: linesep
2449
2450 The string used to separate (or, rather, terminate) lines on the current
Georg Brandl9af94982008-09-13 17:41:16 +00002451 platform. This may be a single character, such as ``'\n'`` for POSIX, or
2452 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
2453 *os.linesep* as a line terminator when writing files opened in text mode (the
2454 default); use a single ``'\n'`` instead, on all platforms.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002455
2456
2457.. data:: devnull
2458
Georg Brandlfa0fdb82010-05-21 22:03:29 +00002459 The file path of the null device. For example: ``'/dev/null'`` for
2460 POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002461
2462 .. versionadded:: 2.4
2463
2464
2465.. _os-miscfunc:
2466
2467Miscellaneous Functions
2468-----------------------
2469
2470
2471.. function:: urandom(n)
2472
2473 Return a string of *n* random bytes suitable for cryptographic use.
2474
2475 This function returns random bytes from an OS-specific randomness source. The
2476 returned data should be unpredictable enough for cryptographic applications,
2477 though its exact quality depends on the OS implementation. On a UNIX-like
2478 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
2479 If a randomness source is not found, :exc:`NotImplementedError` will be raised.
2480
2481 .. versionadded:: 2.4
2482