blob: 14ad8f92d61fdf7ca96aca3a53964b75ae91f453 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`os` --- Miscellaneous operating system interfaces
2=======================================================
3
4.. module:: os
5 :synopsis: Miscellaneous operating system interfaces.
6
7
Christian Heimesa62da1d2008-01-12 19:39:10 +00008This module provides a portable way of using operating system dependent
9functionality. If you just want to read or write a file see :func:`open`, if
10you want to manipulate paths, see the :mod:`os.path` module, and if you want to
11read all the lines in all the files on the command line see the :mod:`fileinput`
12module. For creating temporary files and directories see the :mod:`tempfile`
13module, and for high-level file and directory handling see the :mod:`shutil`
14module.
Georg Brandl116aa622007-08-15 14:28:22 +000015
Christian Heimesa62da1d2008-01-12 19:39:10 +000016The design of all built-in operating system dependent modules of Python is such
17that as long as the same functionality is available, it uses the same interface;
18for example, the function ``os.stat(path)`` returns stat information about
19*path* in the same format (which happens to have originated with the POSIX
Georg Brandl116aa622007-08-15 14:28:22 +000020interface).
21
22Extensions peculiar to a particular operating system are also available through
23the :mod:`os` module, but using them is of course a threat to portability!
24
Christian Heimesa62da1d2008-01-12 19:39:10 +000025.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000026
Georg Brandlc575c902008-09-13 17:46:05 +000027 If not separately noted, all functions that claim "Availability: Unix" are
28 supported on Mac OS X, which builds on a Unix core.
29
30.. note::
31
Christian Heimesa62da1d2008-01-12 19:39:10 +000032 All functions in this module raise :exc:`OSError` in the case of invalid or
33 inaccessible file names and paths, or other arguments that have the correct
34 type, but are not accepted by the operating system.
Georg Brandl116aa622007-08-15 14:28:22 +000035
Georg Brandl116aa622007-08-15 14:28:22 +000036.. exception:: error
37
Christian Heimesa62da1d2008-01-12 19:39:10 +000038 An alias for the built-in :exc:`OSError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +000039
40
41.. data:: name
42
43 The name of the operating system dependent module imported. The following names
44 have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``,
Skip Montanaro7a98be22007-08-16 14:35:24 +000045 ``'ce'``, ``'java'``.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47
48.. data:: path
49
50 The corresponding operating system dependent standard module for pathname
Georg Brandlc575c902008-09-13 17:46:05 +000051 operations, such as :mod:`posixpath` or :mod:`ntpath`. Thus, given the proper
Georg Brandl116aa622007-08-15 14:28:22 +000052 imports, ``os.path.split(file)`` is equivalent to but more portable than
53 ``posixpath.split(file)``. Note that this is also an importable module: it may
54 be imported directly as :mod:`os.path`.
55
56
57.. _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 Brandlc575c902008-09-13 17:46:05 +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 Brandl116aa622007-08-15 14:28:22 +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 Brandl9afde1c2007-11-01 20:32:30 +000096 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl116aa622007-08-15 14:28:22 +000097 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl9afde1c2007-11-01 20:32:30 +000098 automatically when an item is deleted from ``os.environ``, and when
99 one of the :meth:`pop` or :meth:`clear` methods is called.
100
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102.. function:: chdir(path)
103 fchdir(fd)
104 getcwd()
105 :noindex:
106
107 These functions are described in :ref:`os-file-dir`.
108
109
110.. function:: ctermid()
111
112 Return the filename corresponding to the controlling terminal of the process.
113 Availability: Unix.
114
115
116.. function:: getegid()
117
118 Return the effective group id of the current process. This corresponds to the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000119 "set id" bit on the file being executed in the current process. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000120 Unix.
121
122
123.. function:: geteuid()
124
125 .. index:: single: user; effective id
126
Christian Heimesfaf2f632008-01-06 16:59:19 +0000127 Return the current process's effective user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129
130.. function:: getgid()
131
132 .. index:: single: process; group
133
134 Return the real group id of the current process. Availability: Unix.
135
136
137.. function:: getgroups()
138
139 Return list of supplemental group ids associated with the current process.
140 Availability: Unix.
141
142
143.. function:: getlogin()
144
145 Return the name of the user logged in on the controlling terminal of the
146 process. For most purposes, it is more useful to use the environment variable
147 :envvar:`LOGNAME` to find out who the user is, or
148 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
Christian Heimesfaf2f632008-01-06 16:59:19 +0000149 effective user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000150
151
152.. function:: getpgid(pid)
153
154 Return the process group id of the process with process id *pid*. If *pid* is 0,
155 the process group id of the current process is returned. Availability: Unix.
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158.. function:: getpgrp()
159
160 .. index:: single: process; group
161
162 Return the id of the current process group. Availability: Unix.
163
164
165.. function:: getpid()
166
167 .. index:: single: process; id
168
169 Return the current process id. Availability: Unix, Windows.
170
171
172.. function:: getppid()
173
174 .. index:: single: process; id of parent
175
176 Return the parent's process id. Availability: Unix.
177
178
179.. function:: getuid()
180
181 .. index:: single: user; id
182
Christian Heimesfaf2f632008-01-06 16:59:19 +0000183 Return the current process's user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185
186.. function:: getenv(varname[, value])
187
188 Return the value of the environment variable *varname* if it exists, or *value*
189 if it doesn't. *value* defaults to ``None``. Availability: most flavors of
190 Unix, Windows.
191
192
193.. function:: putenv(varname, value)
194
195 .. index:: single: environment variables; setting
196
197 Set the environment variable named *varname* to the string *value*. Such
198 changes to the environment affect subprocesses started with :func:`os.system`,
199 :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
200 Unix, Windows.
201
202 .. note::
203
Georg Brandlc575c902008-09-13 17:46:05 +0000204 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
205 cause memory leaks. Refer to the system documentation for putenv.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
208 automatically translated into corresponding calls to :func:`putenv`; however,
209 calls to :func:`putenv` don't update ``os.environ``, so it is actually
210 preferable to assign to items of ``os.environ``.
211
212
213.. function:: setegid(egid)
214
215 Set the current process's effective group id. Availability: Unix.
216
217
218.. function:: seteuid(euid)
219
220 Set the current process's effective user id. Availability: Unix.
221
222
223.. function:: setgid(gid)
224
225 Set the current process' group id. Availability: Unix.
226
227
228.. function:: setgroups(groups)
229
230 Set the list of supplemental group ids associated with the current process to
231 *groups*. *groups* must be a sequence, and each element must be an integer
Christian Heimesfaf2f632008-01-06 16:59:19 +0000232 identifying a group. This operation is typically available only to the superuser.
Georg Brandl116aa622007-08-15 14:28:22 +0000233 Availability: Unix.
234
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236.. function:: setpgrp()
237
Christian Heimesfaf2f632008-01-06 16:59:19 +0000238 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
Georg Brandl116aa622007-08-15 14:28:22 +0000239 which version is implemented (if any). See the Unix manual for the semantics.
240 Availability: Unix.
241
242
243.. function:: setpgid(pid, pgrp)
244
Christian Heimesfaf2f632008-01-06 16:59:19 +0000245 Call the system call :cfunc:`setpgid` to set the process group id of the
Georg Brandl116aa622007-08-15 14:28:22 +0000246 process with id *pid* to the process group with id *pgrp*. See the Unix manual
247 for the semantics. Availability: Unix.
248
249
250.. function:: setreuid(ruid, euid)
251
252 Set the current process's real and effective user ids. Availability: Unix.
253
254
255.. function:: setregid(rgid, egid)
256
257 Set the current process's real and effective group ids. Availability: Unix.
258
259
260.. function:: getsid(pid)
261
Christian Heimesfaf2f632008-01-06 16:59:19 +0000262 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000263 Availability: Unix.
264
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266.. function:: setsid()
267
Christian Heimesfaf2f632008-01-06 16:59:19 +0000268 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000269 Availability: Unix.
270
271
272.. function:: setuid(uid)
273
274 .. index:: single: user; id, setting
275
Christian Heimesfaf2f632008-01-06 16:59:19 +0000276 Set the current process's user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000277
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000279.. placed in this section since it relates to errno.... a little weak
Georg Brandl116aa622007-08-15 14:28:22 +0000280.. function:: strerror(code)
281
282 Return the error message corresponding to the error code in *code*.
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000283 On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
284 error number, :exc:`ValueError` is raised. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286
287.. function:: umask(mask)
288
Christian Heimesfaf2f632008-01-06 16:59:19 +0000289 Set the current numeric umask and return the previous umask. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000290 Unix, Windows.
291
292
293.. function:: uname()
294
295 .. index::
296 single: gethostname() (in module socket)
297 single: gethostbyaddr() (in module socket)
298
299 Return a 5-tuple containing information identifying the current operating
300 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
301 machine)``. Some systems truncate the nodename to 8 characters or to the
302 leading component; a better way to get the hostname is
303 :func:`socket.gethostname` or even
304 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
305 Unix.
306
307
308.. function:: unsetenv(varname)
309
310 .. index:: single: environment variables; deleting
311
312 Unset (delete) the environment variable named *varname*. Such changes to the
313 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
314 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
315
316 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
317 automatically translated into a corresponding call to :func:`unsetenv`; however,
318 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
319 preferable to delete items of ``os.environ``.
320
321
322.. _os-newstreams:
323
324File Object Creation
325--------------------
326
327These functions create new file objects. (See also :func:`open`.)
328
329
330.. function:: fdopen(fd[, mode[, bufsize]])
331
332 .. index:: single: I/O control; buffering
333
334 Return an open file object connected to the file descriptor *fd*. The *mode*
335 and *bufsize* arguments have the same meaning as the corresponding arguments to
Georg Brandlc575c902008-09-13 17:46:05 +0000336 the built-in :func:`open` function. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000337
Georg Brandl55ac8f02007-09-01 13:51:09 +0000338 When specified, the *mode* argument must start with one of the letters
339 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Georg Brandl55ac8f02007-09-01 13:51:09 +0000341 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
342 set on the file descriptor (which the :cfunc:`fdopen` implementation already
343 does on most platforms).
Georg Brandl116aa622007-08-15 14:28:22 +0000344
345
Georg Brandl116aa622007-08-15 14:28:22 +0000346.. _os-fd-ops:
347
348File Descriptor Operations
349--------------------------
350
351These functions operate on I/O streams referenced using file descriptors.
352
353File descriptors are small integers corresponding to a file that has been opened
354by the current process. For example, standard input is usually file descriptor
3550, standard output is 1, and standard error is 2. Further files opened by a
356process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
357is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
358by file descriptors.
359
360
361.. function:: close(fd)
362
Georg Brandlc575c902008-09-13 17:46:05 +0000363 Close file descriptor *fd*. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365 .. note::
366
367 This function is intended for low-level I/O and must be applied to a file
368 descriptor as returned by :func:`open` or :func:`pipe`. To close a "file
369 object" returned by the built-in function :func:`open` or by :func:`popen` or
370 :func:`fdopen`, use its :meth:`close` method.
371
372
Christian Heimesfdab48e2008-01-20 09:06:41 +0000373.. function:: closerange(fd_low, fd_high)
374
375 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
Georg Brandlc575c902008-09-13 17:46:05 +0000376 ignoring errors. Availability: Unix, Windows. Equivalent to::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000377
378 for fd in xrange(fd_low, fd_high):
379 try:
380 os.close(fd)
381 except OSError:
382 pass
383
Christian Heimesfdab48e2008-01-20 09:06:41 +0000384
Georg Brandl81f11302007-12-21 08:45:42 +0000385.. function:: device_encoding(fd)
386
387 Return a string describing the encoding of the device associated with *fd*
388 if it is connected to a terminal; else return :const:`None`.
389
390
Georg Brandl116aa622007-08-15 14:28:22 +0000391.. function:: dup(fd)
392
Georg Brandlc575c902008-09-13 17:46:05 +0000393 Return a duplicate of file descriptor *fd*. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +0000394 Windows.
395
396
397.. function:: dup2(fd, fd2)
398
399 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
Georg Brandlc575c902008-09-13 17:46:05 +0000400 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402
Christian Heimes4e30a842007-11-30 22:12:06 +0000403.. function:: fchmod(fd, mode)
404
405 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
406 for :func:`chmod` for possible values of *mode*. Availability: Unix.
407
408
409.. function:: fchown(fd, uid, gid)
410
411 Change the owner and group id of the file given by *fd* to the numeric *uid*
412 and *gid*. To leave one of the ids unchanged, set it to -1.
413 Availability: Unix.
414
415
Georg Brandl116aa622007-08-15 14:28:22 +0000416.. function:: fdatasync(fd)
417
418 Force write of file with filedescriptor *fd* to disk. Does not force update of
419 metadata. Availability: Unix.
420
421
422.. function:: fpathconf(fd, name)
423
424 Return system configuration information relevant to an open file. *name*
425 specifies the configuration value to retrieve; it may be a string which is the
426 name of a defined system value; these names are specified in a number of
427 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
428 additional names as well. The names known to the host operating system are
429 given in the ``pathconf_names`` dictionary. For configuration variables not
430 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandlc575c902008-09-13 17:46:05 +0000431 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
434 specific value for *name* is not supported by the host system, even if it is
435 included in ``pathconf_names``, an :exc:`OSError` is raised with
436 :const:`errno.EINVAL` for the error number.
437
438
439.. function:: fstat(fd)
440
441 Return status for file descriptor *fd*, like :func:`stat`. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000442 Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000443
444
445.. function:: fstatvfs(fd)
446
447 Return information about the filesystem containing the file associated with file
448 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
449
450
451.. function:: fsync(fd)
452
453 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
454 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
455
456 If you're starting with a Python file object *f*, first do ``f.flush()``, and
457 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
Georg Brandlc575c902008-09-13 17:46:05 +0000458 with *f* are written to disk. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000459
460
461.. function:: ftruncate(fd, length)
462
463 Truncate the file corresponding to file descriptor *fd*, so that it is at most
Georg Brandlc575c902008-09-13 17:46:05 +0000464 *length* bytes in size. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
466
467.. function:: isatty(fd)
468
469 Return ``True`` if the file descriptor *fd* is open and connected to a
Georg Brandlc575c902008-09-13 17:46:05 +0000470 tty(-like) device, else ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472
473.. function:: lseek(fd, pos, how)
474
Christian Heimesfaf2f632008-01-06 16:59:19 +0000475 Set the current position of file descriptor *fd* to position *pos*, modified
476 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
477 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
478 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Georg Brandlc575c902008-09-13 17:46:05 +0000479 the file. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000480
481
482.. function:: open(file, flags[, mode])
483
Georg Brandlf4a41232008-05-26 17:55:52 +0000484 Open the file *file* and set various flags according to *flags* and possibly
485 its mode according to *mode*. The default *mode* is ``0o777`` (octal), and
486 the current umask value is first masked out. Return the file descriptor for
Georg Brandlc575c902008-09-13 17:46:05 +0000487 the newly opened file. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489 For a description of the flag and mode values, see the C run-time documentation;
490 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
491 this module too (see below).
492
493 .. note::
494
495 This function is intended for low-level I/O. For normal usage, use the built-in
496 function :func:`open`, which returns a "file object" with :meth:`read` and
497 :meth:`write` methods (and many more). To wrap a file descriptor in a "file
498 object", use :func:`fdopen`.
499
500
501.. function:: openpty()
502
503 .. index:: module: pty
504
505 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
506 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Georg Brandlc575c902008-09-13 17:46:05 +0000507 approach, use the :mod:`pty` module. Availability: some flavors of
Georg Brandl116aa622007-08-15 14:28:22 +0000508 Unix.
509
510
511.. function:: pipe()
512
513 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
Georg Brandlc575c902008-09-13 17:46:05 +0000514 and writing, respectively. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516
517.. function:: read(fd, n)
518
519 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
520 bytes read. If the end of the file referred to by *fd* has been reached, an
Georg Brandlc575c902008-09-13 17:46:05 +0000521 empty string is returned. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000522
523 .. note::
524
525 This function is intended for low-level I/O and must be applied to a file
526 descriptor as returned by :func:`open` or :func:`pipe`. To read a "file object"
527 returned by the built-in function :func:`open` or by :func:`popen` or
Christian Heimesfaf2f632008-01-06 16:59:19 +0000528 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`read` or :meth:`readline`
Georg Brandl116aa622007-08-15 14:28:22 +0000529 methods.
530
531
532.. function:: tcgetpgrp(fd)
533
534 Return the process group associated with the terminal given by *fd* (an open
Georg Brandlc575c902008-09-13 17:46:05 +0000535 file descriptor as returned by :func:`open`). Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000536
537
538.. function:: tcsetpgrp(fd, pg)
539
540 Set the process group associated with the terminal given by *fd* (an open file
Georg Brandlc575c902008-09-13 17:46:05 +0000541 descriptor as returned by :func:`open`) to *pg*. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000542
543
544.. function:: ttyname(fd)
545
546 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +0000547 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Georg Brandlc575c902008-09-13 17:46:05 +0000548 exception is raised. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000549
550
551.. function:: write(fd, str)
552
553 Write the string *str* to file descriptor *fd*. Return the number of bytes
Georg Brandlc575c902008-09-13 17:46:05 +0000554 actually written. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556 .. note::
557
558 This function is intended for low-level I/O and must be applied to a file
559 descriptor as returned by :func:`open` or :func:`pipe`. To write a "file
560 object" returned by the built-in function :func:`open` or by :func:`popen` or
Christian Heimesfaf2f632008-01-06 16:59:19 +0000561 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`write`
Georg Brandl116aa622007-08-15 14:28:22 +0000562 method.
563
564The following data items are available for use in constructing the *flags*
565parameter to the :func:`open` function. Some items will not be available on all
566platforms. For descriptions of their availability and use, consult
567:manpage:`open(2)`.
568
569
570.. data:: O_RDONLY
571 O_WRONLY
572 O_RDWR
573 O_APPEND
574 O_CREAT
575 O_EXCL
576 O_TRUNC
577
578 Options for the *flag* argument to the :func:`open` function. These can be
Georg Brandlc575c902008-09-13 17:46:05 +0000579 combined using the bitwise OR operator ``|``. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000580
581
582.. data:: O_DSYNC
583 O_RSYNC
584 O_SYNC
585 O_NDELAY
586 O_NONBLOCK
587 O_NOCTTY
588 O_SHLOCK
589 O_EXLOCK
590
591 More options for the *flag* argument to the :func:`open` function. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000592 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000593
594
595.. data:: O_BINARY
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000596 O_NOINHERIT
Georg Brandl116aa622007-08-15 14:28:22 +0000597 O_SHORT_LIVED
598 O_TEMPORARY
599 O_RANDOM
600 O_SEQUENTIAL
601 O_TEXT
602
603 Options for the *flag* argument to the :func:`open` function. These can be
Christian Heimesfaf2f632008-01-06 16:59:19 +0000604 combined using the bitwise OR operator ``|``. Availability: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000605
606
Alexandre Vassalottibee32532008-05-16 18:15:12 +0000607.. data:: O_ASYNC
608 O_DIRECT
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000609 O_DIRECTORY
610 O_NOFOLLOW
611 O_NOATIME
612
613 Options for the *flag* argument to the :func:`open` function. These are
614 GNU extensions and not present if they are not defined by the C library.
615
616
Georg Brandl116aa622007-08-15 14:28:22 +0000617.. data:: SEEK_SET
618 SEEK_CUR
619 SEEK_END
620
621 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
Georg Brandlc575c902008-09-13 17:46:05 +0000622 respectively. Availability: Windows, Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000623
Georg Brandl116aa622007-08-15 14:28:22 +0000624
625.. _os-file-dir:
626
627Files and Directories
628---------------------
629
Georg Brandl116aa622007-08-15 14:28:22 +0000630.. function:: access(path, mode)
631
632 Use the real uid/gid to test for access to *path*. Note that most operations
633 will use the effective uid/gid, therefore this routine can be used in a
634 suid/sgid environment to test if the invoking user has the specified access to
635 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
636 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
637 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
638 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
Georg Brandlc575c902008-09-13 17:46:05 +0000639 information. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000640
641 .. note::
642
643 Using :func:`access` to check if a user is authorized to e.g. open a file before
644 actually doing so using :func:`open` creates a security hole, because the user
645 might exploit the short time interval between checking and opening the file to
646 manipulate it.
647
648 .. note::
649
650 I/O operations may fail even when :func:`access` indicates that they would
651 succeed, particularly for operations on network filesystems which may have
652 permissions semantics beyond the usual POSIX permission-bit model.
653
654
655.. data:: F_OK
656
657 Value to pass as the *mode* parameter of :func:`access` to test the existence of
658 *path*.
659
660
661.. data:: R_OK
662
663 Value to include in the *mode* parameter of :func:`access` to test the
664 readability of *path*.
665
666
667.. data:: W_OK
668
669 Value to include in the *mode* parameter of :func:`access` to test the
670 writability of *path*.
671
672
673.. data:: X_OK
674
675 Value to include in the *mode* parameter of :func:`access` to determine if
676 *path* can be executed.
677
678
679.. function:: chdir(path)
680
681 .. index:: single: directory; changing
682
Georg Brandlc575c902008-09-13 17:46:05 +0000683 Change the current working directory to *path*. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +0000684 Windows.
685
686
687.. function:: fchdir(fd)
688
689 Change the current working directory to the directory represented by the file
690 descriptor *fd*. The descriptor must refer to an opened directory, not an open
691 file. Availability: Unix.
692
Georg Brandl116aa622007-08-15 14:28:22 +0000693
694.. function:: getcwd()
695
Martin v. Löwisa731b992008-10-07 06:36:31 +0000696 Return a string representing the current working directory.
Martin v. Löwis651423c2008-10-07 07:03:04 +0000697 May raise UnicodeDecodeError if the current directory path fails
698 to decode in the file system encoding.
Georg Brandlc575c902008-09-13 17:46:05 +0000699 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000700
701
Martin v. Löwisa731b992008-10-07 06:36:31 +0000702.. function:: getcwdb()
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Martin v. Löwisa731b992008-10-07 06:36:31 +0000704 Return a bytestring representing the current working directory.
Georg Brandlc575c902008-09-13 17:46:05 +0000705 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000706
Georg Brandl116aa622007-08-15 14:28:22 +0000707
708.. function:: chflags(path, flags)
709
710 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
711 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
712
713 * ``UF_NODUMP``
714 * ``UF_IMMUTABLE``
715 * ``UF_APPEND``
716 * ``UF_OPAQUE``
717 * ``UF_NOUNLINK``
718 * ``SF_ARCHIVED``
719 * ``SF_IMMUTABLE``
720 * ``SF_APPEND``
721 * ``SF_NOUNLINK``
722 * ``SF_SNAPSHOT``
723
Georg Brandlc575c902008-09-13 17:46:05 +0000724 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Georg Brandl116aa622007-08-15 14:28:22 +0000726
727.. function:: chroot(path)
728
729 Change the root directory of the current process to *path*. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000730 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000731
Georg Brandl116aa622007-08-15 14:28:22 +0000732
733.. function:: chmod(path, mode)
734
735 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000736 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl116aa622007-08-15 14:28:22 +0000737 combinations of them:
738
739 * ``stat.S_ISUID``
740 * ``stat.S_ISGID``
741 * ``stat.S_ENFMT``
742 * ``stat.S_ISVTX``
743 * ``stat.S_IREAD``
744 * ``stat.S_IWRITE``
745 * ``stat.S_IEXEC``
746 * ``stat.S_IRWXU``
747 * ``stat.S_IRUSR``
748 * ``stat.S_IWUSR``
749 * ``stat.S_IXUSR``
750 * ``stat.S_IRWXG``
751 * ``stat.S_IRGRP``
752 * ``stat.S_IWGRP``
753 * ``stat.S_IXGRP``
754 * ``stat.S_IRWXO``
755 * ``stat.S_IROTH``
756 * ``stat.S_IWOTH``
757 * ``stat.S_IXOTH``
758
Georg Brandlc575c902008-09-13 17:46:05 +0000759 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000760
761 .. note::
762
763 Although Windows supports :func:`chmod`, you can only set the file's read-only
764 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
765 constants or a corresponding integer value). All other bits are
766 ignored.
767
768
769.. function:: chown(path, uid, gid)
770
771 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
Georg Brandlc575c902008-09-13 17:46:05 +0000772 one of the ids unchanged, set it to -1. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774
775.. function:: lchflags(path, flags)
776
777 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
778 follow symbolic links. Availability: Unix.
779
Georg Brandl116aa622007-08-15 14:28:22 +0000780
Christian Heimes93852662007-12-01 12:22:32 +0000781.. function:: lchmod(path, mode)
782
783 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
784 affects the symlink rather than the target. See the docs for :func:`chmod`
785 for possible values of *mode*. Availability: Unix.
786
Christian Heimes93852662007-12-01 12:22:32 +0000787
Georg Brandl116aa622007-08-15 14:28:22 +0000788.. function:: lchown(path, uid, gid)
789
Christian Heimesfaf2f632008-01-06 16:59:19 +0000790 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Georg Brandlc575c902008-09-13 17:46:05 +0000791 function will not follow symbolic links. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000792
Georg Brandl116aa622007-08-15 14:28:22 +0000793
794.. function:: link(src, dst)
795
Georg Brandlc575c902008-09-13 17:46:05 +0000796 Create a hard link pointing to *src* named *dst*. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000797
798
799.. function:: listdir(path)
800
801 Return a list containing the names of the entries in the directory. The list is
802 in arbitrary order. It does not include the special entries ``'.'`` and
Georg Brandlc575c902008-09-13 17:46:05 +0000803 ``'..'`` even if they are present in the directory. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000804 Unix, Windows.
805
Martin v. Löwisa731b992008-10-07 06:36:31 +0000806 If *path* is a Unicode object, the result will be a list of Unicode objects.
807 If a filename can not be decoded to unicode, it is skipped. If *path* is a
808 bytes string, the result will be list of bytes objects included files
809 skipped by the unicode version.
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811
812.. function:: lstat(path)
813
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000814 Like :func:`stat`, but do not follow symbolic links. This is an alias for
815 :func:`stat` on platforms that do not support symbolic links, such as
816 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000817
818
819.. function:: mkfifo(path[, mode])
820
Georg Brandlf4a41232008-05-26 17:55:52 +0000821 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The
822 default *mode* is ``0o666`` (octal). The current umask value is first masked
Georg Brandlc575c902008-09-13 17:46:05 +0000823 out from the mode. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000824
825 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
826 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
827 rendezvous between "client" and "server" type processes: the server opens the
828 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
829 doesn't open the FIFO --- it just creates the rendezvous point.
830
831
Georg Brandlf4a41232008-05-26 17:55:52 +0000832.. function:: mknod(filename[, mode=0o600, device])
Georg Brandl116aa622007-08-15 14:28:22 +0000833
834 Create a filesystem node (file, device special file or named pipe) named
835 *filename*. *mode* specifies both the permissions to use and the type of node to
836 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
837 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
838 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
839 For ``stat.S_IFCHR`` and
840 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
841 :func:`os.makedev`), otherwise it is ignored.
842
Georg Brandl116aa622007-08-15 14:28:22 +0000843
844.. function:: major(device)
845
Christian Heimesfaf2f632008-01-06 16:59:19 +0000846 Extract the device major number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +0000847 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
848
Georg Brandl116aa622007-08-15 14:28:22 +0000849
850.. function:: minor(device)
851
Christian Heimesfaf2f632008-01-06 16:59:19 +0000852 Extract the device minor number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +0000853 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
854
Georg Brandl116aa622007-08-15 14:28:22 +0000855
856.. function:: makedev(major, minor)
857
Christian Heimesfaf2f632008-01-06 16:59:19 +0000858 Compose a raw device number from the major and minor device numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000859
Georg Brandl116aa622007-08-15 14:28:22 +0000860
861.. function:: mkdir(path[, mode])
862
Georg Brandlf4a41232008-05-26 17:55:52 +0000863 Create a directory named *path* with numeric mode *mode*. The default *mode*
864 is ``0o777`` (octal). On some systems, *mode* is ignored. Where it is used,
Georg Brandlc575c902008-09-13 17:46:05 +0000865 the current umask value is first masked out. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000866
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000867 It is also possible to create temporary directories; see the
868 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
869
Georg Brandl116aa622007-08-15 14:28:22 +0000870
871.. function:: makedirs(path[, mode])
872
873 .. index::
874 single: directory; creating
875 single: UNC paths; and os.makedirs()
876
877 Recursive directory creation function. Like :func:`mkdir`, but makes all
Georg Brandlf4a41232008-05-26 17:55:52 +0000878 intermediate-level directories needed to contain the leaf directory. Throws
879 an :exc:`error` exception if the leaf directory already exists or cannot be
880 created. The default *mode* is ``0o777`` (octal). On some systems, *mode*
881 is ignored. Where it is used, the current umask value is first masked out.
Georg Brandl116aa622007-08-15 14:28:22 +0000882
883 .. note::
884
885 :func:`makedirs` will become confused if the path elements to create include
Christian Heimesfaf2f632008-01-06 16:59:19 +0000886 :data:`os.pardir`.
Georg Brandl116aa622007-08-15 14:28:22 +0000887
Georg Brandl55ac8f02007-09-01 13:51:09 +0000888 This function handles UNC paths correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000889
890
891.. function:: pathconf(path, name)
892
893 Return system configuration information relevant to a named file. *name*
894 specifies the configuration value to retrieve; it may be a string which is the
895 name of a defined system value; these names are specified in a number of
896 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
897 additional names as well. The names known to the host operating system are
898 given in the ``pathconf_names`` dictionary. For configuration variables not
899 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandlc575c902008-09-13 17:46:05 +0000900 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000901
902 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
903 specific value for *name* is not supported by the host system, even if it is
904 included in ``pathconf_names``, an :exc:`OSError` is raised with
905 :const:`errno.EINVAL` for the error number.
906
907
908.. data:: pathconf_names
909
910 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
911 the integer values defined for those names by the host operating system. This
912 can be used to determine the set of names known to the system. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000913 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000914
915
916.. function:: readlink(path)
917
918 Return a string representing the path to which the symbolic link points. The
919 result may be either an absolute or relative pathname; if it is relative, it may
920 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
921 result)``.
922
Martin v. Löwisa731b992008-10-07 06:36:31 +0000923 If the *path* is an Unicode object, the result will also be a Unicode object
924 and may raise an UnicodeDecodeError. If the *path* is a bytes object, the
925 result will be a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Georg Brandlc575c902008-09-13 17:46:05 +0000927 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000928
929
930.. function:: remove(path)
931
932 Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
933 :func:`rmdir` below to remove a directory. This is identical to the
934 :func:`unlink` function documented below. On Windows, attempting to remove a
935 file that is in use causes an exception to be raised; on Unix, the directory
936 entry is removed but the storage allocated to the file is not made available
Georg Brandlc575c902008-09-13 17:46:05 +0000937 until the original file is no longer in use. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +0000938 Windows.
939
940
941.. function:: removedirs(path)
942
943 .. index:: single: directory; deleting
944
Christian Heimesfaf2f632008-01-06 16:59:19 +0000945 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000946 leaf directory is successfully removed, :func:`removedirs` tries to
947 successively remove every parent directory mentioned in *path* until an error
948 is raised (which is ignored, because it generally means that a parent directory
949 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
950 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
951 they are empty. Raises :exc:`OSError` if the leaf directory could not be
952 successfully removed.
953
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955.. function:: rename(src, dst)
956
957 Rename the file or directory *src* to *dst*. If *dst* is a directory,
958 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Christian Heimesfaf2f632008-01-06 16:59:19 +0000959 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl116aa622007-08-15 14:28:22 +0000960 Unix flavors if *src* and *dst* are on different filesystems. If successful,
961 the renaming will be an atomic operation (this is a POSIX requirement). On
962 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
963 file; there may be no way to implement an atomic rename when *dst* names an
Georg Brandlc575c902008-09-13 17:46:05 +0000964 existing file. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000965
966
967.. function:: renames(old, new)
968
969 Recursive directory or file renaming function. Works like :func:`rename`, except
970 creation of any intermediate directories needed to make the new pathname good is
971 attempted first. After the rename, directories corresponding to rightmost path
972 segments of the old name will be pruned away using :func:`removedirs`.
973
Georg Brandl116aa622007-08-15 14:28:22 +0000974 .. note::
975
976 This function can fail with the new directory structure made if you lack
977 permissions needed to remove the leaf directory or file.
978
979
980.. function:: rmdir(path)
981
Georg Brandlc575c902008-09-13 17:46:05 +0000982 Remove the directory *path*. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000983
984
985.. function:: stat(path)
986
987 Perform a :cfunc:`stat` system call on the given path. The return value is an
988 object whose attributes correspond to the members of the :ctype:`stat`
989 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
990 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
Christian Heimesfaf2f632008-01-06 16:59:19 +0000991 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
Georg Brandl116aa622007-08-15 14:28:22 +0000992 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
993 access), :attr:`st_mtime` (time of most recent content modification),
994 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
995 Unix, or the time of creation on Windows)::
996
997 >>> import os
998 >>> statinfo = os.stat('somefile.txt')
999 >>> statinfo
1000 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1001 >>> statinfo.st_size
1002 926L
1003 >>>
1004
Georg Brandl116aa622007-08-15 14:28:22 +00001005
1006 On some Unix systems (such as Linux), the following attributes may also be
1007 available: :attr:`st_blocks` (number of blocks allocated for file),
1008 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1009 inode device). :attr:`st_flags` (user defined flags for file).
1010
1011 On other Unix systems (such as FreeBSD), the following attributes may be
1012 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1013 (file generation number), :attr:`st_birthtime` (time of file creation).
1014
1015 On Mac OS systems, the following attributes may also be available:
1016 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1017
Georg Brandl116aa622007-08-15 14:28:22 +00001018 .. index:: module: stat
1019
1020 For backward compatibility, the return value of :func:`stat` is also accessible
1021 as a tuple of at least 10 integers giving the most important (and portable)
1022 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1023 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1024 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1025 :attr:`st_ctime`. More items may be added at the end by some implementations.
1026 The standard module :mod:`stat` defines functions and constants that are useful
1027 for extracting information from a :ctype:`stat` structure. (On Windows, some
1028 items are filled with dummy values.)
1029
1030 .. note::
1031
1032 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1033 :attr:`st_ctime` members depends on the operating system and the file system.
1034 For example, on Windows systems using the FAT or FAT32 file systems,
1035 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1036 resolution. See your operating system documentation for details.
1037
Georg Brandlc575c902008-09-13 17:46:05 +00001038 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001039
Georg Brandl116aa622007-08-15 14:28:22 +00001040
1041.. function:: stat_float_times([newvalue])
1042
1043 Determine whether :class:`stat_result` represents time stamps as float objects.
1044 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1045 ``False``, future calls return ints. If *newvalue* is omitted, return the
1046 current setting.
1047
1048 For compatibility with older Python versions, accessing :class:`stat_result` as
1049 a tuple always returns integers.
1050
Georg Brandl55ac8f02007-09-01 13:51:09 +00001051 Python now returns float values by default. Applications which do not work
1052 correctly with floating point time stamps can use this function to restore the
1053 old behaviour.
Georg Brandl116aa622007-08-15 14:28:22 +00001054
1055 The resolution of the timestamps (that is the smallest possible fraction)
1056 depends on the system. Some systems only support second resolution; on these
1057 systems, the fraction will always be zero.
1058
1059 It is recommended that this setting is only changed at program startup time in
1060 the *__main__* module; libraries should never change this setting. If an
1061 application uses a library that works incorrectly if floating point time stamps
1062 are processed, this application should turn the feature off until the library
1063 has been corrected.
1064
1065
1066.. function:: statvfs(path)
1067
1068 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1069 an object whose attributes describe the filesystem on the given path, and
1070 correspond to the members of the :ctype:`statvfs` structure, namely:
1071 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1072 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1073 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1074
Georg Brandl116aa622007-08-15 14:28:22 +00001075
1076.. function:: symlink(src, dst)
1077
1078 Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
1079
1080
Georg Brandl116aa622007-08-15 14:28:22 +00001081.. function:: unlink(path)
1082
1083 Remove the file *path*. This is the same function as :func:`remove`; the
Georg Brandlc575c902008-09-13 17:46:05 +00001084 :func:`unlink` name is its traditional Unix name. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +00001085 Windows.
1086
1087
1088.. function:: utime(path, times)
1089
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00001090 Set the access and modified times of the file specified by *path*. If *times*
1091 is ``None``, then the file's access and modified times are set to the current
1092 time. (The effect is similar to running the Unix program :program:`touch` on
1093 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1094 ``(atime, mtime)`` which is used to set the access and modified times,
1095 respectively. Whether a directory can be given for *path* depends on whether
1096 the operating system implements directories as files (for example, Windows
1097 does not). Note that the exact times you set here may not be returned by a
1098 subsequent :func:`stat` call, depending on the resolution with which your
1099 operating system records access and modification times; see :func:`stat`.
Georg Brandl116aa622007-08-15 14:28:22 +00001100
Georg Brandlc575c902008-09-13 17:46:05 +00001101 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001102
1103
1104.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1105
1106 .. index::
1107 single: directory; walking
1108 single: directory; traversal
1109
Christian Heimesfaf2f632008-01-06 16:59:19 +00001110 Generate the file names in a directory tree by walking the tree
1111 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl116aa622007-08-15 14:28:22 +00001112 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1113 filenames)``.
1114
1115 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1116 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1117 *filenames* is a list of the names of the non-directory files in *dirpath*.
1118 Note that the names in the lists contain no path components. To get a full path
1119 (which begins with *top*) to a file or directory in *dirpath*, do
1120 ``os.path.join(dirpath, name)``.
1121
Christian Heimesfaf2f632008-01-06 16:59:19 +00001122 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001123 directory is generated before the triples for any of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001124 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001125 directory is generated after the triples for all of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001126 (directories are generated bottom-up).
Georg Brandl116aa622007-08-15 14:28:22 +00001127
Christian Heimesfaf2f632008-01-06 16:59:19 +00001128 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl116aa622007-08-15 14:28:22 +00001129 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1130 recurse into the subdirectories whose names remain in *dirnames*; this can be
1131 used to prune the search, impose a specific order of visiting, or even to inform
1132 :func:`walk` about directories the caller creates or renames before it resumes
Christian Heimesfaf2f632008-01-06 16:59:19 +00001133 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl116aa622007-08-15 14:28:22 +00001134 ineffective, because in bottom-up mode the directories in *dirnames* are
1135 generated before *dirpath* itself is generated.
1136
Christian Heimesfaf2f632008-01-06 16:59:19 +00001137 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl116aa622007-08-15 14:28:22 +00001138 argument *onerror* is specified, it should be a function; it will be called with
1139 one argument, an :exc:`OSError` instance. It can report the error to continue
1140 with the walk, or raise the exception to abort the walk. Note that the filename
1141 is available as the ``filename`` attribute of the exception object.
1142
1143 By default, :func:`walk` will not walk down into symbolic links that resolve to
Christian Heimesfaf2f632008-01-06 16:59:19 +00001144 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl116aa622007-08-15 14:28:22 +00001145 symlinks, on systems that support them.
1146
Georg Brandl116aa622007-08-15 14:28:22 +00001147 .. note::
1148
Christian Heimesfaf2f632008-01-06 16:59:19 +00001149 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl116aa622007-08-15 14:28:22 +00001150 link points to a parent directory of itself. :func:`walk` does not keep track of
1151 the directories it visited already.
1152
1153 .. note::
1154
1155 If you pass a relative pathname, don't change the current working directory
1156 between resumptions of :func:`walk`. :func:`walk` never changes the current
1157 directory, and assumes that its caller doesn't either.
1158
1159 This example displays the number of bytes taken by non-directory files in each
1160 directory under the starting directory, except that it doesn't look under any
1161 CVS subdirectory::
1162
1163 import os
1164 from os.path import join, getsize
1165 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001166 print(root, "consumes", end=" ")
1167 print(sum(getsize(join(root, name)) for name in files), end=" ")
1168 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00001169 if 'CVS' in dirs:
1170 dirs.remove('CVS') # don't visit CVS directories
1171
Christian Heimesfaf2f632008-01-06 16:59:19 +00001172 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl116aa622007-08-15 14:28:22 +00001173 doesn't allow deleting a directory before the directory is empty::
1174
Christian Heimesfaf2f632008-01-06 16:59:19 +00001175 # Delete everything reachable from the directory named in "top",
Georg Brandl116aa622007-08-15 14:28:22 +00001176 # assuming there are no symbolic links.
1177 # CAUTION: This is dangerous! For example, if top == '/', it
1178 # could delete all your disk files.
1179 import os
1180 for root, dirs, files in os.walk(top, topdown=False):
1181 for name in files:
1182 os.remove(os.path.join(root, name))
1183 for name in dirs:
1184 os.rmdir(os.path.join(root, name))
1185
Georg Brandl116aa622007-08-15 14:28:22 +00001186
1187.. _os-process:
1188
1189Process Management
1190------------------
1191
1192These functions may be used to create and manage processes.
1193
1194The various :func:`exec\*` functions take a list of arguments for the new
1195program loaded into the process. In each case, the first of these arguments is
1196passed to the new program as its own name rather than as an argument a user may
1197have typed on a command line. For the C programmer, this is the ``argv[0]``
1198passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1199['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1200to be ignored.
1201
1202
1203.. function:: abort()
1204
1205 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1206 behavior is to produce a core dump; on Windows, the process immediately returns
1207 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1208 to register a handler for :const:`SIGABRT` will behave differently.
Georg Brandlc575c902008-09-13 17:46:05 +00001209 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001210
1211
1212.. function:: execl(path, arg0, arg1, ...)
1213 execle(path, arg0, arg1, ..., env)
1214 execlp(file, arg0, arg1, ...)
1215 execlpe(file, arg0, arg1, ..., env)
1216 execv(path, args)
1217 execve(path, args, env)
1218 execvp(file, args)
1219 execvpe(file, args, env)
1220
1221 These functions all execute a new program, replacing the current process; they
1222 do not return. On Unix, the new executable is loaded into the current process,
Christian Heimesfaf2f632008-01-06 16:59:19 +00001223 and will have the same process id as the caller. Errors will be reported as
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001224 :exc:`OSError` exceptions.
1225
1226 The current process is replaced immediately. Open file objects and
1227 descriptors are not flushed, so if there may be data buffered
1228 on these open files, you should flush them using
1229 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
1230 :func:`exec\*` function.
Georg Brandl116aa622007-08-15 14:28:22 +00001231
Christian Heimesfaf2f632008-01-06 16:59:19 +00001232 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1233 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001234 to work with if the number of parameters is fixed when the code is written; the
1235 individual parameters simply become additional parameters to the :func:`execl\*`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001236 functions. The "v" variants are good when the number of parameters is
Georg Brandl116aa622007-08-15 14:28:22 +00001237 variable, with the arguments being passed in a list or tuple as the *args*
1238 parameter. In either case, the arguments to the child process should start with
1239 the name of the command being run, but this is not enforced.
1240
Christian Heimesfaf2f632008-01-06 16:59:19 +00001241 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001242 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1243 :envvar:`PATH` environment variable to locate the program *file*. When the
1244 environment is being replaced (using one of the :func:`exec\*e` variants,
1245 discussed in the next paragraph), the new environment is used as the source of
1246 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1247 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1248 locate the executable; *path* must contain an appropriate absolute or relative
1249 path.
1250
1251 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Christian Heimesfaf2f632008-01-06 16:59:19 +00001252 that these all end in "e"), the *env* parameter must be a mapping which is
Christian Heimesa342c012008-04-20 21:01:16 +00001253 used to define the environment variables for the new process (these are used
1254 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl116aa622007-08-15 14:28:22 +00001255 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001256 inherit the environment of the current process.
1257
1258 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001259
1260
1261.. function:: _exit(n)
1262
1263 Exit to the system with status *n*, without calling cleanup handlers, flushing
Georg Brandlc575c902008-09-13 17:46:05 +00001264 stdio buffers, etc. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001265
1266 .. note::
1267
1268 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1269 be used in the child process after a :func:`fork`.
1270
Christian Heimesfaf2f632008-01-06 16:59:19 +00001271The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl116aa622007-08-15 14:28:22 +00001272although they are not required. These are typically used for system programs
1273written in Python, such as a mail server's external command delivery program.
1274
1275.. note::
1276
1277 Some of these may not be available on all Unix platforms, since there is some
1278 variation. These constants are defined where they are defined by the underlying
1279 platform.
1280
1281
1282.. data:: EX_OK
1283
Georg Brandlc575c902008-09-13 17:46:05 +00001284 Exit code that means no error occurred. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001285
Georg Brandl116aa622007-08-15 14:28:22 +00001286
1287.. data:: EX_USAGE
1288
1289 Exit code that means the command was used incorrectly, such as when the wrong
Georg Brandlc575c902008-09-13 17:46:05 +00001290 number of arguments are given. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001291
Georg Brandl116aa622007-08-15 14:28:22 +00001292
1293.. data:: EX_DATAERR
1294
Georg Brandlc575c902008-09-13 17:46:05 +00001295 Exit code that means the input data was incorrect. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001296
Georg Brandl116aa622007-08-15 14:28:22 +00001297
1298.. data:: EX_NOINPUT
1299
1300 Exit code that means an input file did not exist or was not readable.
Georg Brandlc575c902008-09-13 17:46:05 +00001301 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001302
Georg Brandl116aa622007-08-15 14:28:22 +00001303
1304.. data:: EX_NOUSER
1305
Georg Brandlc575c902008-09-13 17:46:05 +00001306 Exit code that means a specified user did not exist. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001307
Georg Brandl116aa622007-08-15 14:28:22 +00001308
1309.. data:: EX_NOHOST
1310
Georg Brandlc575c902008-09-13 17:46:05 +00001311 Exit code that means a specified host did not exist. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001312
Georg Brandl116aa622007-08-15 14:28:22 +00001313
1314.. data:: EX_UNAVAILABLE
1315
1316 Exit code that means that a required service is unavailable. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001317 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001318
Georg Brandl116aa622007-08-15 14:28:22 +00001319
1320.. data:: EX_SOFTWARE
1321
1322 Exit code that means an internal software error was detected. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001323 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001324
Georg Brandl116aa622007-08-15 14:28:22 +00001325
1326.. data:: EX_OSERR
1327
1328 Exit code that means an operating system error was detected, such as the
Georg Brandlc575c902008-09-13 17:46:05 +00001329 inability to fork or create a pipe. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001330
Georg Brandl116aa622007-08-15 14:28:22 +00001331
1332.. data:: EX_OSFILE
1333
1334 Exit code that means some system file did not exist, could not be opened, or had
Georg Brandlc575c902008-09-13 17:46:05 +00001335 some other kind of error. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001336
Georg Brandl116aa622007-08-15 14:28:22 +00001337
1338.. data:: EX_CANTCREAT
1339
1340 Exit code that means a user specified output file could not be created.
Georg Brandlc575c902008-09-13 17:46:05 +00001341 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001342
Georg Brandl116aa622007-08-15 14:28:22 +00001343
1344.. data:: EX_IOERR
1345
1346 Exit code that means that an error occurred while doing I/O on some file.
Georg Brandlc575c902008-09-13 17:46:05 +00001347 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001348
Georg Brandl116aa622007-08-15 14:28:22 +00001349
1350.. data:: EX_TEMPFAIL
1351
1352 Exit code that means a temporary failure occurred. This indicates something
1353 that may not really be an error, such as a network connection that couldn't be
Georg Brandlc575c902008-09-13 17:46:05 +00001354 made during a retryable operation. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001355
Georg Brandl116aa622007-08-15 14:28:22 +00001356
1357.. data:: EX_PROTOCOL
1358
1359 Exit code that means that a protocol exchange was illegal, invalid, or not
Georg Brandlc575c902008-09-13 17:46:05 +00001360 understood. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001361
Georg Brandl116aa622007-08-15 14:28:22 +00001362
1363.. data:: EX_NOPERM
1364
1365 Exit code that means that there were insufficient permissions to perform the
Georg Brandlc575c902008-09-13 17:46:05 +00001366 operation (but not intended for file system problems). Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001367
Georg Brandl116aa622007-08-15 14:28:22 +00001368
1369.. data:: EX_CONFIG
1370
1371 Exit code that means that some kind of configuration error occurred.
Georg Brandlc575c902008-09-13 17:46:05 +00001372 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001373
Georg Brandl116aa622007-08-15 14:28:22 +00001374
1375.. data:: EX_NOTFOUND
1376
1377 Exit code that means something like "an entry was not found". Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001378 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001379
Georg Brandl116aa622007-08-15 14:28:22 +00001380
1381.. function:: fork()
1382
Christian Heimesfaf2f632008-01-06 16:59:19 +00001383 Fork a child process. Return ``0`` in the child and the child's process id in the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001384 parent. If an error occurs :exc:`OSError` is raised.
Georg Brandlc575c902008-09-13 17:46:05 +00001385 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001386
1387
1388.. function:: forkpty()
1389
1390 Fork a child process, using a new pseudo-terminal as the child's controlling
1391 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1392 new child's process id in the parent, and *fd* is the file descriptor of the
1393 master end of the pseudo-terminal. For a more portable approach, use the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001394 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
Georg Brandlc575c902008-09-13 17:46:05 +00001395 Availability: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001396
1397
1398.. function:: kill(pid, sig)
1399
1400 .. index::
1401 single: process; killing
1402 single: process; signalling
1403
1404 Send signal *sig* to the process *pid*. Constants for the specific signals
1405 available on the host platform are defined in the :mod:`signal` module.
Georg Brandlc575c902008-09-13 17:46:05 +00001406 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001407
1408
1409.. function:: killpg(pgid, sig)
1410
1411 .. index::
1412 single: process; killing
1413 single: process; signalling
1414
Georg Brandlc575c902008-09-13 17:46:05 +00001415 Send the signal *sig* to the process group *pgid*. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001416
Georg Brandl116aa622007-08-15 14:28:22 +00001417
1418.. function:: nice(increment)
1419
1420 Add *increment* to the process's "niceness". Return the new niceness.
Georg Brandlc575c902008-09-13 17:46:05 +00001421 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001422
1423
1424.. function:: plock(op)
1425
1426 Lock program segments into memory. The value of *op* (defined in
Georg Brandlc575c902008-09-13 17:46:05 +00001427 ``<sys/lock.h>``) determines which segments are locked. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001428
1429
1430.. function:: popen(...)
1431 :noindex:
1432
1433 Run child processes, returning opened pipes for communications. These functions
1434 are described in section :ref:`os-newstreams`.
1435
1436
1437.. function:: spawnl(mode, path, ...)
1438 spawnle(mode, path, ..., env)
1439 spawnlp(mode, file, ...)
1440 spawnlpe(mode, file, ..., env)
1441 spawnv(mode, path, args)
1442 spawnve(mode, path, args, env)
1443 spawnvp(mode, file, args)
1444 spawnvpe(mode, file, args, env)
1445
1446 Execute the program *path* in a new process.
1447
1448 (Note that the :mod:`subprocess` module provides more powerful facilities for
1449 spawning new processes and retrieving their results; using that module is
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001450 preferable to using these functions. Check specially the *Replacing Older
1451 Functions with the subprocess Module* section in that documentation page.)
Georg Brandl116aa622007-08-15 14:28:22 +00001452
Christian Heimesfaf2f632008-01-06 16:59:19 +00001453 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl116aa622007-08-15 14:28:22 +00001454 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1455 exits normally, or ``-signal``, where *signal* is the signal that killed the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001456 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl116aa622007-08-15 14:28:22 +00001457 be used with the :func:`waitpid` function.
1458
Christian Heimesfaf2f632008-01-06 16:59:19 +00001459 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1460 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001461 to work with if the number of parameters is fixed when the code is written; the
1462 individual parameters simply become additional parameters to the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001463 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl116aa622007-08-15 14:28:22 +00001464 parameters is variable, with the arguments being passed in a list or tuple as
1465 the *args* parameter. In either case, the arguments to the child process must
1466 start with the name of the command being run.
1467
Christian Heimesfaf2f632008-01-06 16:59:19 +00001468 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001469 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1470 :envvar:`PATH` environment variable to locate the program *file*. When the
1471 environment is being replaced (using one of the :func:`spawn\*e` variants,
1472 discussed in the next paragraph), the new environment is used as the source of
1473 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1474 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1475 :envvar:`PATH` variable to locate the executable; *path* must contain an
1476 appropriate absolute or relative path.
1477
1478 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001479 (note that these all end in "e"), the *env* parameter must be a mapping
Christian Heimesa342c012008-04-20 21:01:16 +00001480 which is used to define the environment variables for the new process (they are
1481 used instead of the current process' environment); the functions
Georg Brandl116aa622007-08-15 14:28:22 +00001482 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1483 the new process to inherit the environment of the current process.
1484
1485 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1486 equivalent::
1487
1488 import os
1489 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1490
1491 L = ['cp', 'index.html', '/dev/null']
1492 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1493
1494 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1495 and :func:`spawnvpe` are not available on Windows.
1496
Georg Brandl116aa622007-08-15 14:28:22 +00001497
1498.. data:: P_NOWAIT
1499 P_NOWAITO
1500
1501 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1502 functions. If either of these values is given, the :func:`spawn\*` functions
Christian Heimesfaf2f632008-01-06 16:59:19 +00001503 will return as soon as the new process has been created, with the process id as
Georg Brandlc575c902008-09-13 17:46:05 +00001504 the return value. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001505
Georg Brandl116aa622007-08-15 14:28:22 +00001506
1507.. data:: P_WAIT
1508
1509 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1510 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1511 return until the new process has run to completion and will return the exit code
1512 of the process the run is successful, or ``-signal`` if a signal kills the
Georg Brandlc575c902008-09-13 17:46:05 +00001513 process. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001514
Georg Brandl116aa622007-08-15 14:28:22 +00001515
1516.. data:: P_DETACH
1517 P_OVERLAY
1518
1519 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1520 functions. These are less portable than those listed above. :const:`P_DETACH`
1521 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1522 console of the calling process. If :const:`P_OVERLAY` is used, the current
1523 process will be replaced; the :func:`spawn\*` function will not return.
1524 Availability: Windows.
1525
Georg Brandl116aa622007-08-15 14:28:22 +00001526
1527.. function:: startfile(path[, operation])
1528
1529 Start a file with its associated application.
1530
1531 When *operation* is not specified or ``'open'``, this acts like double-clicking
1532 the file in Windows Explorer, or giving the file name as an argument to the
1533 :program:`start` command from the interactive command shell: the file is opened
1534 with whatever application (if any) its extension is associated.
1535
1536 When another *operation* is given, it must be a "command verb" that specifies
1537 what should be done with the file. Common verbs documented by Microsoft are
1538 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1539 ``'find'`` (to be used on directories).
1540
1541 :func:`startfile` returns as soon as the associated application is launched.
1542 There is no option to wait for the application to close, and no way to retrieve
1543 the application's exit status. The *path* parameter is relative to the current
1544 directory. If you want to use an absolute path, make sure the first character
1545 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1546 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1547 the path is properly encoded for Win32. Availability: Windows.
1548
Georg Brandl116aa622007-08-15 14:28:22 +00001549
1550.. function:: system(command)
1551
1552 Execute the command (a string) in a subshell. This is implemented by calling
1553 the Standard C function :cfunc:`system`, and has the same limitations. Changes
Christian Heimesfaf2f632008-01-06 16:59:19 +00001554 to :data:`os.environ`, :data:`sys.stdin`, etc. are not reflected in the
1555 environment of the executed command.
Georg Brandl116aa622007-08-15 14:28:22 +00001556
1557 On Unix, the return value is the exit status of the process encoded in the
1558 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1559 of the return value of the C :cfunc:`system` function, so the return value of
1560 the Python function is system-dependent.
1561
1562 On Windows, the return value is that returned by the system shell after running
1563 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1564 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1565 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1566 the command run; on systems using a non-native shell, consult your shell
1567 documentation.
1568
Georg Brandlc575c902008-09-13 17:46:05 +00001569 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001570
1571 The :mod:`subprocess` module provides more powerful facilities for spawning new
1572 processes and retrieving their results; using that module is preferable to using
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001573 this function. Use the :mod:`subprocess` module. Check especially the
1574 :ref:`subprocess-replacements` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001575
1576
1577.. function:: times()
1578
1579 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1580 other) times, in seconds. The items are: user time, system time, children's
1581 user time, children's system time, and elapsed real time since a fixed point in
1582 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
Georg Brandlc575c902008-09-13 17:46:05 +00001583 corresponding Windows Platform API documentation. Availability: Unix,
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001584 Windows. On Windows, only the first two items are filled, the others are zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001585
1586
1587.. function:: wait()
1588
1589 Wait for completion of a child process, and return a tuple containing its pid
1590 and exit status indication: a 16-bit number, whose low byte is the signal number
1591 that killed the process, and whose high byte is the exit status (if the signal
1592 number is zero); the high bit of the low byte is set if a core file was
Georg Brandlc575c902008-09-13 17:46:05 +00001593 produced. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001594
1595
1596.. function:: waitpid(pid, options)
1597
1598 The details of this function differ on Unix and Windows.
1599
1600 On Unix: Wait for completion of a child process given by process id *pid*, and
1601 return a tuple containing its process id and exit status indication (encoded as
1602 for :func:`wait`). The semantics of the call are affected by the value of the
1603 integer *options*, which should be ``0`` for normal operation.
1604
1605 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1606 that specific process. If *pid* is ``0``, the request is for the status of any
1607 child in the process group of the current process. If *pid* is ``-1``, the
1608 request pertains to any child of the current process. If *pid* is less than
1609 ``-1``, status is requested for any process in the process group ``-pid`` (the
1610 absolute value of *pid*).
1611
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00001612 An :exc:`OSError` is raised with the value of errno when the syscall
1613 returns -1.
1614
Georg Brandl116aa622007-08-15 14:28:22 +00001615 On Windows: Wait for completion of a process given by process handle *pid*, and
1616 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1617 (shifting makes cross-platform use of the function easier). A *pid* less than or
1618 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1619 value of integer *options* has no effect. *pid* can refer to any process whose
1620 id is known, not necessarily a child process. The :func:`spawn` functions called
1621 with :const:`P_NOWAIT` return suitable process handles.
1622
1623
1624.. function:: wait3([options])
1625
1626 Similar to :func:`waitpid`, except no process id argument is given and a
1627 3-element tuple containing the child's process id, exit status indication, and
1628 resource usage information is returned. Refer to :mod:`resource`.\
1629 :func:`getrusage` for details on resource usage information. The option
1630 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1631 Availability: Unix.
1632
Georg Brandl116aa622007-08-15 14:28:22 +00001633
1634.. function:: wait4(pid, options)
1635
1636 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1637 process id, exit status indication, and resource usage information is returned.
1638 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1639 information. The arguments to :func:`wait4` are the same as those provided to
1640 :func:`waitpid`. Availability: Unix.
1641
Georg Brandl116aa622007-08-15 14:28:22 +00001642
1643.. data:: WNOHANG
1644
1645 The option for :func:`waitpid` to return immediately if no child process status
1646 is available immediately. The function returns ``(0, 0)`` in this case.
Georg Brandlc575c902008-09-13 17:46:05 +00001647 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001648
1649
1650.. data:: WCONTINUED
1651
1652 This option causes child processes to be reported if they have been continued
1653 from a job control stop since their status was last reported. Availability: Some
1654 Unix systems.
1655
Georg Brandl116aa622007-08-15 14:28:22 +00001656
1657.. data:: WUNTRACED
1658
1659 This option causes child processes to be reported if they have been stopped but
1660 their current state has not been reported since they were stopped. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001661 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001662
Georg Brandl116aa622007-08-15 14:28:22 +00001663
1664The following functions take a process status code as returned by
1665:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1666used to determine the disposition of a process.
1667
Georg Brandl116aa622007-08-15 14:28:22 +00001668.. function:: WCOREDUMP(status)
1669
Christian Heimesfaf2f632008-01-06 16:59:19 +00001670 Return ``True`` if a core dump was generated for the process, otherwise
Georg Brandlc575c902008-09-13 17:46:05 +00001671 return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001672
Georg Brandl116aa622007-08-15 14:28:22 +00001673
1674.. function:: WIFCONTINUED(status)
1675
Christian Heimesfaf2f632008-01-06 16:59:19 +00001676 Return ``True`` if the process has been continued from a job control stop,
1677 otherwise return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001678
Georg Brandl116aa622007-08-15 14:28:22 +00001679
1680.. function:: WIFSTOPPED(status)
1681
Christian Heimesfaf2f632008-01-06 16:59:19 +00001682 Return ``True`` if the process has been stopped, otherwise return
Georg Brandl116aa622007-08-15 14:28:22 +00001683 ``False``. Availability: Unix.
1684
1685
1686.. function:: WIFSIGNALED(status)
1687
Christian Heimesfaf2f632008-01-06 16:59:19 +00001688 Return ``True`` if the process exited due to a signal, otherwise return
Georg Brandlc575c902008-09-13 17:46:05 +00001689 ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001690
1691
1692.. function:: WIFEXITED(status)
1693
Christian Heimesfaf2f632008-01-06 16:59:19 +00001694 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
Georg Brandlc575c902008-09-13 17:46:05 +00001695 otherwise return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001696
1697
1698.. function:: WEXITSTATUS(status)
1699
1700 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1701 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
Georg Brandlc575c902008-09-13 17:46:05 +00001702 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001703
1704
1705.. function:: WSTOPSIG(status)
1706
Georg Brandlc575c902008-09-13 17:46:05 +00001707 Return the signal which caused the process to stop. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001708
1709
1710.. function:: WTERMSIG(status)
1711
Georg Brandlc575c902008-09-13 17:46:05 +00001712 Return the signal which caused the process to exit. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001713
1714
1715.. _os-path:
1716
1717Miscellaneous System Information
1718--------------------------------
1719
1720
1721.. function:: confstr(name)
1722
1723 Return string-valued system configuration values. *name* specifies the
1724 configuration value to retrieve; it may be a string which is the name of a
1725 defined system value; these names are specified in a number of standards (POSIX,
1726 Unix 95, Unix 98, and others). Some platforms define additional names as well.
1727 The names known to the host operating system are given as the keys of the
1728 ``confstr_names`` dictionary. For configuration variables not included in that
1729 mapping, passing an integer for *name* is also accepted. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001730 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001731
1732 If the configuration value specified by *name* isn't defined, ``None`` is
1733 returned.
1734
1735 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1736 specific value for *name* is not supported by the host system, even if it is
1737 included in ``confstr_names``, an :exc:`OSError` is raised with
1738 :const:`errno.EINVAL` for the error number.
1739
1740
1741.. data:: confstr_names
1742
1743 Dictionary mapping names accepted by :func:`confstr` to the integer values
1744 defined for those names by the host operating system. This can be used to
Georg Brandlc575c902008-09-13 17:46:05 +00001745 determine the set of names known to the system. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001746
1747
1748.. function:: getloadavg()
1749
Christian Heimesa62da1d2008-01-12 19:39:10 +00001750 Return the number of processes in the system run queue averaged over the last
1751 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001752 unobtainable. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001753
Georg Brandl116aa622007-08-15 14:28:22 +00001754
1755.. function:: sysconf(name)
1756
1757 Return integer-valued system configuration values. If the configuration value
1758 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
1759 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
1760 provides information on the known names is given by ``sysconf_names``.
Georg Brandlc575c902008-09-13 17:46:05 +00001761 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001762
1763
1764.. data:: sysconf_names
1765
1766 Dictionary mapping names accepted by :func:`sysconf` to the integer values
1767 defined for those names by the host operating system. This can be used to
Georg Brandlc575c902008-09-13 17:46:05 +00001768 determine the set of names known to the system. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001769
Christian Heimesfaf2f632008-01-06 16:59:19 +00001770The following data values are used to support path manipulation operations. These
Georg Brandl116aa622007-08-15 14:28:22 +00001771are defined for all platforms.
1772
1773Higher-level operations on pathnames are defined in the :mod:`os.path` module.
1774
1775
1776.. data:: curdir
1777
1778 The constant string used by the operating system to refer to the current
Georg Brandlc575c902008-09-13 17:46:05 +00001779 directory. This is ``'.'`` for Windows and POSIX. Also available via
1780 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00001781
1782
1783.. data:: pardir
1784
1785 The constant string used by the operating system to refer to the parent
Georg Brandlc575c902008-09-13 17:46:05 +00001786 directory. This is ``'..'`` for Windows and POSIX. Also available via
1787 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00001788
1789
1790.. data:: sep
1791
Georg Brandlc575c902008-09-13 17:46:05 +00001792 The character used by the operating system to separate pathname components.
1793 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
1794 is not sufficient to be able to parse or concatenate pathnames --- use
Georg Brandl116aa622007-08-15 14:28:22 +00001795 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
1796 useful. Also available via :mod:`os.path`.
1797
1798
1799.. data:: altsep
1800
1801 An alternative character used by the operating system to separate pathname
1802 components, or ``None`` if only one separator character exists. This is set to
1803 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
1804 :mod:`os.path`.
1805
1806
1807.. data:: extsep
1808
1809 The character which separates the base filename from the extension; for example,
1810 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
1811
Georg Brandl116aa622007-08-15 14:28:22 +00001812
1813.. data:: pathsep
1814
1815 The character conventionally used by the operating system to separate search
1816 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
1817 Windows. Also available via :mod:`os.path`.
1818
1819
1820.. data:: defpath
1821
1822 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
1823 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
1824
1825
1826.. data:: linesep
1827
1828 The string used to separate (or, rather, terminate) lines on the current
Georg Brandlc575c902008-09-13 17:46:05 +00001829 platform. This may be a single character, such as ``'\n'`` for POSIX, or
1830 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
1831 *os.linesep* as a line terminator when writing files opened in text mode (the
1832 default); use a single ``'\n'`` instead, on all platforms.
Georg Brandl116aa622007-08-15 14:28:22 +00001833
1834
1835.. data:: devnull
1836
Georg Brandlc575c902008-09-13 17:46:05 +00001837 The file path of the null device. For example: ``'/dev/null'`` for POSIX.
1838 Also available via :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00001839
Georg Brandl116aa622007-08-15 14:28:22 +00001840
1841.. _os-miscfunc:
1842
1843Miscellaneous Functions
1844-----------------------
1845
1846
1847.. function:: urandom(n)
1848
1849 Return a string of *n* random bytes suitable for cryptographic use.
1850
1851 This function returns random bytes from an OS-specific randomness source. The
1852 returned data should be unpredictable enough for cryptographic applications,
1853 though its exact quality depends on the OS implementation. On a UNIX-like
1854 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
1855 If a randomness source is not found, :exc:`NotImplementedError` will be raised.