blob: b95833c3e4a9ac80465d6ad968aab6ee753c35de [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
Christian Heimesa62da1d2008-01-12 19:39:10 +000027 All functions in this module raise :exc:`OSError` in the case of invalid or
28 inaccessible file names and paths, or other arguments that have the correct
29 type, but are not accepted by the operating system.
Georg Brandl116aa622007-08-15 14:28:22 +000030
Georg Brandl116aa622007-08-15 14:28:22 +000031.. exception:: error
32
Christian Heimesa62da1d2008-01-12 19:39:10 +000033 An alias for the built-in :exc:`OSError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +000034
35
36.. data:: name
37
38 The name of the operating system dependent module imported. The following names
39 have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``,
Skip Montanaro7a98be22007-08-16 14:35:24 +000040 ``'ce'``, ``'java'``.
Georg Brandl116aa622007-08-15 14:28:22 +000041
42
43.. data:: path
44
45 The corresponding operating system dependent standard module for pathname
46 operations, such as :mod:`posixpath` or :mod:`macpath`. Thus, given the proper
47 imports, ``os.path.split(file)`` is equivalent to but more portable than
48 ``posixpath.split(file)``. Note that this is also an importable module: it may
49 be imported directly as :mod:`os.path`.
50
51
52.. _os-procinfo:
53
54Process Parameters
55------------------
56
57These functions and data items provide information and operate on the current
58process and user.
59
60
61.. data:: environ
62
63 A mapping object representing the string environment. For example,
64 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
65 and is equivalent to ``getenv("HOME")`` in C.
66
67 This mapping is captured the first time the :mod:`os` module is imported,
68 typically during Python startup as part of processing :file:`site.py`. Changes
69 to the environment made after this time are not reflected in ``os.environ``,
70 except for changes made by modifying ``os.environ`` directly.
71
72 If the platform supports the :func:`putenv` function, this mapping may be used
73 to modify the environment as well as query the environment. :func:`putenv` will
74 be called automatically when the mapping is modified.
75
76 .. note::
77
78 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
79 to modify ``os.environ``.
80
81 .. note::
82
83 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause
84 memory leaks. Refer to the system documentation for :cfunc:`putenv`.
85
86 If :func:`putenv` is not provided, a modified copy of this mapping may be
87 passed to the appropriate process-creation functions to cause child processes
88 to use a modified environment.
89
Georg Brandl9afde1c2007-11-01 20:32:30 +000090 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl116aa622007-08-15 14:28:22 +000091 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl9afde1c2007-11-01 20:32:30 +000092 automatically when an item is deleted from ``os.environ``, and when
93 one of the :meth:`pop` or :meth:`clear` methods is called.
94
Georg Brandl116aa622007-08-15 14:28:22 +000095
96.. function:: chdir(path)
97 fchdir(fd)
98 getcwd()
99 :noindex:
100
101 These functions are described in :ref:`os-file-dir`.
102
103
104.. function:: ctermid()
105
106 Return the filename corresponding to the controlling terminal of the process.
107 Availability: Unix.
108
109
110.. function:: getegid()
111
112 Return the effective group id of the current process. This corresponds to the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000113 "set id" bit on the file being executed in the current process. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000114 Unix.
115
116
117.. function:: geteuid()
118
119 .. index:: single: user; effective id
120
Christian Heimesfaf2f632008-01-06 16:59:19 +0000121 Return the current process's effective user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123
124.. function:: getgid()
125
126 .. index:: single: process; group
127
128 Return the real group id of the current process. Availability: Unix.
129
130
131.. function:: getgroups()
132
133 Return list of supplemental group ids associated with the current process.
134 Availability: Unix.
135
136
137.. function:: getlogin()
138
139 Return the name of the user logged in on the controlling terminal of the
140 process. For most purposes, it is more useful to use the environment variable
141 :envvar:`LOGNAME` to find out who the user is, or
142 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
Christian Heimesfaf2f632008-01-06 16:59:19 +0000143 effective user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145
146.. function:: getpgid(pid)
147
148 Return the process group id of the process with process id *pid*. If *pid* is 0,
149 the process group id of the current process is returned. Availability: Unix.
150
Georg Brandl116aa622007-08-15 14:28:22 +0000151
152.. function:: getpgrp()
153
154 .. index:: single: process; group
155
156 Return the id of the current process group. Availability: Unix.
157
158
159.. function:: getpid()
160
161 .. index:: single: process; id
162
163 Return the current process id. Availability: Unix, Windows.
164
165
166.. function:: getppid()
167
168 .. index:: single: process; id of parent
169
170 Return the parent's process id. Availability: Unix.
171
172
173.. function:: getuid()
174
175 .. index:: single: user; id
176
Christian Heimesfaf2f632008-01-06 16:59:19 +0000177 Return the current process's user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000178
179
180.. function:: getenv(varname[, value])
181
182 Return the value of the environment variable *varname* if it exists, or *value*
183 if it doesn't. *value* defaults to ``None``. Availability: most flavors of
184 Unix, Windows.
185
186
187.. function:: putenv(varname, value)
188
189 .. index:: single: environment variables; setting
190
191 Set the environment variable named *varname* to the string *value*. Such
192 changes to the environment affect subprocesses started with :func:`os.system`,
193 :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
194 Unix, Windows.
195
196 .. note::
197
198 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause
199 memory leaks. Refer to the system documentation for putenv.
200
201 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
202 automatically translated into corresponding calls to :func:`putenv`; however,
203 calls to :func:`putenv` don't update ``os.environ``, so it is actually
204 preferable to assign to items of ``os.environ``.
205
206
207.. function:: setegid(egid)
208
209 Set the current process's effective group id. Availability: Unix.
210
211
212.. function:: seteuid(euid)
213
214 Set the current process's effective user id. Availability: Unix.
215
216
217.. function:: setgid(gid)
218
219 Set the current process' group id. Availability: Unix.
220
221
222.. function:: setgroups(groups)
223
224 Set the list of supplemental group ids associated with the current process to
225 *groups*. *groups* must be a sequence, and each element must be an integer
Christian Heimesfaf2f632008-01-06 16:59:19 +0000226 identifying a group. This operation is typically available only to the superuser.
Georg Brandl116aa622007-08-15 14:28:22 +0000227 Availability: Unix.
228
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230.. function:: setpgrp()
231
Christian Heimesfaf2f632008-01-06 16:59:19 +0000232 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
Georg Brandl116aa622007-08-15 14:28:22 +0000233 which version is implemented (if any). See the Unix manual for the semantics.
234 Availability: Unix.
235
236
237.. function:: setpgid(pid, pgrp)
238
Christian Heimesfaf2f632008-01-06 16:59:19 +0000239 Call the system call :cfunc:`setpgid` to set the process group id of the
Georg Brandl116aa622007-08-15 14:28:22 +0000240 process with id *pid* to the process group with id *pgrp*. See the Unix manual
241 for the semantics. Availability: Unix.
242
243
244.. function:: setreuid(ruid, euid)
245
246 Set the current process's real and effective user ids. Availability: Unix.
247
248
249.. function:: setregid(rgid, egid)
250
251 Set the current process's real and effective group ids. Availability: Unix.
252
253
254.. function:: getsid(pid)
255
Christian Heimesfaf2f632008-01-06 16:59:19 +0000256 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000257 Availability: Unix.
258
Georg Brandl116aa622007-08-15 14:28:22 +0000259
260.. function:: setsid()
261
Christian Heimesfaf2f632008-01-06 16:59:19 +0000262 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000263 Availability: Unix.
264
265
266.. function:: setuid(uid)
267
268 .. index:: single: user; id, setting
269
Christian Heimesfaf2f632008-01-06 16:59:19 +0000270 Set the current process's user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000271
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000273.. placed in this section since it relates to errno.... a little weak
Georg Brandl116aa622007-08-15 14:28:22 +0000274.. function:: strerror(code)
275
276 Return the error message corresponding to the error code in *code*.
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000277 On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
278 error number, :exc:`ValueError` is raised. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280
281.. function:: umask(mask)
282
Christian Heimesfaf2f632008-01-06 16:59:19 +0000283 Set the current numeric umask and return the previous umask. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000284 Unix, Windows.
285
286
287.. function:: uname()
288
289 .. index::
290 single: gethostname() (in module socket)
291 single: gethostbyaddr() (in module socket)
292
293 Return a 5-tuple containing information identifying the current operating
294 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
295 machine)``. Some systems truncate the nodename to 8 characters or to the
296 leading component; a better way to get the hostname is
297 :func:`socket.gethostname` or even
298 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
299 Unix.
300
301
302.. function:: unsetenv(varname)
303
304 .. index:: single: environment variables; deleting
305
306 Unset (delete) the environment variable named *varname*. Such changes to the
307 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
308 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
309
310 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
311 automatically translated into a corresponding call to :func:`unsetenv`; however,
312 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
313 preferable to delete items of ``os.environ``.
314
315
316.. _os-newstreams:
317
318File Object Creation
319--------------------
320
321These functions create new file objects. (See also :func:`open`.)
322
323
324.. function:: fdopen(fd[, mode[, bufsize]])
325
326 .. index:: single: I/O control; buffering
327
328 Return an open file object connected to the file descriptor *fd*. The *mode*
329 and *bufsize* arguments have the same meaning as the corresponding arguments to
330 the built-in :func:`open` function. Availability: Macintosh, Unix, Windows.
331
Georg Brandl55ac8f02007-09-01 13:51:09 +0000332 When specified, the *mode* argument must start with one of the letters
333 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000334
Georg Brandl55ac8f02007-09-01 13:51:09 +0000335 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
336 set on the file descriptor (which the :cfunc:`fdopen` implementation already
337 does on most platforms).
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339
Georg Brandl116aa622007-08-15 14:28:22 +0000340.. _os-fd-ops:
341
342File Descriptor Operations
343--------------------------
344
345These functions operate on I/O streams referenced using file descriptors.
346
347File descriptors are small integers corresponding to a file that has been opened
348by the current process. For example, standard input is usually file descriptor
3490, standard output is 1, and standard error is 2. Further files opened by a
350process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
351is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
352by file descriptors.
353
354
355.. function:: close(fd)
356
357 Close file descriptor *fd*. Availability: Macintosh, Unix, Windows.
358
359 .. note::
360
361 This function is intended for low-level I/O and must be applied to a file
362 descriptor as returned by :func:`open` or :func:`pipe`. To close a "file
363 object" returned by the built-in function :func:`open` or by :func:`popen` or
364 :func:`fdopen`, use its :meth:`close` method.
365
366
Christian Heimesfdab48e2008-01-20 09:06:41 +0000367.. function:: closerange(fd_low, fd_high)
368
369 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
370 ignoring errors. Availability: Macintosh, Unix, Windows. Equivalent to::
371
372 for fd in xrange(fd_low, fd_high):
373 try:
374 os.close(fd)
375 except OSError:
376 pass
377
Christian Heimesfdab48e2008-01-20 09:06:41 +0000378
Georg Brandl81f11302007-12-21 08:45:42 +0000379.. function:: device_encoding(fd)
380
381 Return a string describing the encoding of the device associated with *fd*
382 if it is connected to a terminal; else return :const:`None`.
383
384
Georg Brandl116aa622007-08-15 14:28:22 +0000385.. function:: dup(fd)
386
387 Return a duplicate of file descriptor *fd*. Availability: Macintosh, Unix,
388 Windows.
389
390
391.. function:: dup2(fd, fd2)
392
393 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
394 Availability: Macintosh, Unix, Windows.
395
396
Christian Heimes4e30a842007-11-30 22:12:06 +0000397.. function:: fchmod(fd, mode)
398
399 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
400 for :func:`chmod` for possible values of *mode*. Availability: Unix.
401
402
403.. function:: fchown(fd, uid, gid)
404
405 Change the owner and group id of the file given by *fd* to the numeric *uid*
406 and *gid*. To leave one of the ids unchanged, set it to -1.
407 Availability: Unix.
408
409
Georg Brandl116aa622007-08-15 14:28:22 +0000410.. function:: fdatasync(fd)
411
412 Force write of file with filedescriptor *fd* to disk. Does not force update of
413 metadata. Availability: Unix.
414
415
416.. function:: fpathconf(fd, name)
417
418 Return system configuration information relevant to an open file. *name*
419 specifies the configuration value to retrieve; it may be a string which is the
420 name of a defined system value; these names are specified in a number of
421 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
422 additional names as well. The names known to the host operating system are
423 given in the ``pathconf_names`` dictionary. For configuration variables not
424 included in that mapping, passing an integer for *name* is also accepted.
425 Availability: Macintosh, Unix.
426
427 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
428 specific value for *name* is not supported by the host system, even if it is
429 included in ``pathconf_names``, an :exc:`OSError` is raised with
430 :const:`errno.EINVAL` for the error number.
431
432
433.. function:: fstat(fd)
434
435 Return status for file descriptor *fd*, like :func:`stat`. Availability:
436 Macintosh, Unix, Windows.
437
438
439.. function:: fstatvfs(fd)
440
441 Return information about the filesystem containing the file associated with file
442 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
443
444
445.. function:: fsync(fd)
446
447 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
448 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
449
450 If you're starting with a Python file object *f*, first do ``f.flush()``, and
451 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
Georg Brandle6bcc912008-05-12 18:05:20 +0000452 with *f* are written to disk. Availability: Macintosh, Unix, and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000453
454
455.. function:: ftruncate(fd, length)
456
457 Truncate the file corresponding to file descriptor *fd*, so that it is at most
458 *length* bytes in size. Availability: Macintosh, Unix.
459
460
461.. function:: isatty(fd)
462
463 Return ``True`` if the file descriptor *fd* is open and connected to a
464 tty(-like) device, else ``False``. Availability: Macintosh, Unix.
465
466
467.. function:: lseek(fd, pos, how)
468
Christian Heimesfaf2f632008-01-06 16:59:19 +0000469 Set the current position of file descriptor *fd* to position *pos*, modified
470 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
471 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
472 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Georg Brandl116aa622007-08-15 14:28:22 +0000473 the file. Availability: Macintosh, Unix, Windows.
474
475
476.. function:: open(file, flags[, mode])
477
Georg Brandlf4a41232008-05-26 17:55:52 +0000478 Open the file *file* and set various flags according to *flags* and possibly
479 its mode according to *mode*. The default *mode* is ``0o777`` (octal), and
480 the current umask value is first masked out. Return the file descriptor for
481 the newly opened file. Availability: Macintosh, Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000482
483 For a description of the flag and mode values, see the C run-time documentation;
484 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
485 this module too (see below).
486
487 .. note::
488
489 This function is intended for low-level I/O. For normal usage, use the built-in
490 function :func:`open`, which returns a "file object" with :meth:`read` and
491 :meth:`write` methods (and many more). To wrap a file descriptor in a "file
492 object", use :func:`fdopen`.
493
494
495.. function:: openpty()
496
497 .. index:: module: pty
498
499 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
500 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Christian Heimesfaf2f632008-01-06 16:59:19 +0000501 approach, use the :mod:`pty` module. Availability: Macintosh, some flavors of
Georg Brandl116aa622007-08-15 14:28:22 +0000502 Unix.
503
504
505.. function:: pipe()
506
507 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
508 and writing, respectively. Availability: Macintosh, Unix, Windows.
509
510
511.. function:: read(fd, n)
512
513 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
514 bytes read. If the end of the file referred to by *fd* has been reached, an
515 empty string is returned. Availability: Macintosh, Unix, Windows.
516
517 .. note::
518
519 This function is intended for low-level I/O and must be applied to a file
520 descriptor as returned by :func:`open` or :func:`pipe`. To read a "file object"
521 returned by the built-in function :func:`open` or by :func:`popen` or
Christian Heimesfaf2f632008-01-06 16:59:19 +0000522 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`read` or :meth:`readline`
Georg Brandl116aa622007-08-15 14:28:22 +0000523 methods.
524
525
526.. function:: tcgetpgrp(fd)
527
528 Return the process group associated with the terminal given by *fd* (an open
529 file descriptor as returned by :func:`open`). Availability: Macintosh, Unix.
530
531
532.. function:: tcsetpgrp(fd, pg)
533
534 Set the process group associated with the terminal given by *fd* (an open file
535 descriptor as returned by :func:`open`) to *pg*. Availability: Macintosh, Unix.
536
537
538.. function:: ttyname(fd)
539
540 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +0000541 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Georg Brandl116aa622007-08-15 14:28:22 +0000542 exception is raised. Availability:Macintosh, Unix.
543
544
545.. function:: write(fd, str)
546
547 Write the string *str* to file descriptor *fd*. Return the number of bytes
548 actually written. Availability: Macintosh, Unix, Windows.
549
550 .. note::
551
552 This function is intended for low-level I/O and must be applied to a file
553 descriptor as returned by :func:`open` or :func:`pipe`. To write a "file
554 object" returned by the built-in function :func:`open` or by :func:`popen` or
Christian Heimesfaf2f632008-01-06 16:59:19 +0000555 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`write`
Georg Brandl116aa622007-08-15 14:28:22 +0000556 method.
557
558The following data items are available for use in constructing the *flags*
559parameter to the :func:`open` function. Some items will not be available on all
560platforms. For descriptions of their availability and use, consult
561:manpage:`open(2)`.
562
563
564.. data:: O_RDONLY
565 O_WRONLY
566 O_RDWR
567 O_APPEND
568 O_CREAT
569 O_EXCL
570 O_TRUNC
571
572 Options for the *flag* argument to the :func:`open` function. These can be
Christian Heimesfaf2f632008-01-06 16:59:19 +0000573 combined using the bitwise OR operator ``|``. Availability: Macintosh, Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000574
575
576.. data:: O_DSYNC
577 O_RSYNC
578 O_SYNC
579 O_NDELAY
580 O_NONBLOCK
581 O_NOCTTY
582 O_SHLOCK
583 O_EXLOCK
584
585 More options for the *flag* argument to the :func:`open` function. Availability:
586 Macintosh, Unix.
587
588
589.. data:: O_BINARY
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000590 O_NOINHERIT
Georg Brandl116aa622007-08-15 14:28:22 +0000591 O_SHORT_LIVED
592 O_TEMPORARY
593 O_RANDOM
594 O_SEQUENTIAL
595 O_TEXT
596
597 Options for the *flag* argument to the :func:`open` function. These can be
Christian Heimesfaf2f632008-01-06 16:59:19 +0000598 combined using the bitwise OR operator ``|``. Availability: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000599
600
Alexandre Vassalottibee32532008-05-16 18:15:12 +0000601.. data:: O_ASYNC
602 O_DIRECT
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000603 O_DIRECTORY
604 O_NOFOLLOW
605 O_NOATIME
606
607 Options for the *flag* argument to the :func:`open` function. These are
608 GNU extensions and not present if they are not defined by the C library.
609
610
Georg Brandl116aa622007-08-15 14:28:22 +0000611.. data:: SEEK_SET
612 SEEK_CUR
613 SEEK_END
614
615 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
616 respectively. Availability: Windows, Macintosh, Unix.
617
Georg Brandl116aa622007-08-15 14:28:22 +0000618
619.. _os-file-dir:
620
621Files and Directories
622---------------------
623
Georg Brandl116aa622007-08-15 14:28:22 +0000624.. function:: access(path, mode)
625
626 Use the real uid/gid to test for access to *path*. Note that most operations
627 will use the effective uid/gid, therefore this routine can be used in a
628 suid/sgid environment to test if the invoking user has the specified access to
629 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
630 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
631 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
632 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
633 information. Availability: Macintosh, Unix, Windows.
634
635 .. note::
636
637 Using :func:`access` to check if a user is authorized to e.g. open a file before
638 actually doing so using :func:`open` creates a security hole, because the user
639 might exploit the short time interval between checking and opening the file to
640 manipulate it.
641
642 .. note::
643
644 I/O operations may fail even when :func:`access` indicates that they would
645 succeed, particularly for operations on network filesystems which may have
646 permissions semantics beyond the usual POSIX permission-bit model.
647
648
649.. data:: F_OK
650
651 Value to pass as the *mode* parameter of :func:`access` to test the existence of
652 *path*.
653
654
655.. data:: R_OK
656
657 Value to include in the *mode* parameter of :func:`access` to test the
658 readability of *path*.
659
660
661.. data:: W_OK
662
663 Value to include in the *mode* parameter of :func:`access` to test the
664 writability of *path*.
665
666
667.. data:: X_OK
668
669 Value to include in the *mode* parameter of :func:`access` to determine if
670 *path* can be executed.
671
672
673.. function:: chdir(path)
674
675 .. index:: single: directory; changing
676
677 Change the current working directory to *path*. Availability: Macintosh, Unix,
678 Windows.
679
680
681.. function:: fchdir(fd)
682
683 Change the current working directory to the directory represented by the file
684 descriptor *fd*. The descriptor must refer to an opened directory, not an open
685 file. Availability: Unix.
686
Georg Brandl116aa622007-08-15 14:28:22 +0000687
688.. function:: getcwd()
689
Georg Brandlf6945182008-02-01 11:56:49 +0000690 Return a bytestring representing the current working directory.
691 Availability: Macintosh, Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000692
693
694.. function:: getcwdu()
695
Georg Brandlf6945182008-02-01 11:56:49 +0000696 Return a string representing the current working directory.
Georg Brandl116aa622007-08-15 14:28:22 +0000697 Availability: Macintosh, Unix, Windows.
698
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700.. function:: chflags(path, flags)
701
702 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
703 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
704
705 * ``UF_NODUMP``
706 * ``UF_IMMUTABLE``
707 * ``UF_APPEND``
708 * ``UF_OPAQUE``
709 * ``UF_NOUNLINK``
710 * ``SF_ARCHIVED``
711 * ``SF_IMMUTABLE``
712 * ``SF_APPEND``
713 * ``SF_NOUNLINK``
714 * ``SF_SNAPSHOT``
715
716 Availability: Macintosh, Unix.
717
Georg Brandl116aa622007-08-15 14:28:22 +0000718
719.. function:: chroot(path)
720
721 Change the root directory of the current process to *path*. Availability:
722 Macintosh, Unix.
723
Georg Brandl116aa622007-08-15 14:28:22 +0000724
725.. function:: chmod(path, mode)
726
727 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000728 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl116aa622007-08-15 14:28:22 +0000729 combinations of them:
730
731 * ``stat.S_ISUID``
732 * ``stat.S_ISGID``
733 * ``stat.S_ENFMT``
734 * ``stat.S_ISVTX``
735 * ``stat.S_IREAD``
736 * ``stat.S_IWRITE``
737 * ``stat.S_IEXEC``
738 * ``stat.S_IRWXU``
739 * ``stat.S_IRUSR``
740 * ``stat.S_IWUSR``
741 * ``stat.S_IXUSR``
742 * ``stat.S_IRWXG``
743 * ``stat.S_IRGRP``
744 * ``stat.S_IWGRP``
745 * ``stat.S_IXGRP``
746 * ``stat.S_IRWXO``
747 * ``stat.S_IROTH``
748 * ``stat.S_IWOTH``
749 * ``stat.S_IXOTH``
750
751 Availability: Macintosh, Unix, Windows.
752
753 .. note::
754
755 Although Windows supports :func:`chmod`, you can only set the file's read-only
756 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
757 constants or a corresponding integer value). All other bits are
758 ignored.
759
760
761.. function:: chown(path, uid, gid)
762
763 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
764 one of the ids unchanged, set it to -1. Availability: Macintosh, Unix.
765
766
767.. function:: lchflags(path, flags)
768
769 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
770 follow symbolic links. Availability: Unix.
771
Georg Brandl116aa622007-08-15 14:28:22 +0000772
Christian Heimes93852662007-12-01 12:22:32 +0000773.. function:: lchmod(path, mode)
774
775 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
776 affects the symlink rather than the target. See the docs for :func:`chmod`
777 for possible values of *mode*. Availability: Unix.
778
Christian Heimes93852662007-12-01 12:22:32 +0000779
Georg Brandl116aa622007-08-15 14:28:22 +0000780.. function:: lchown(path, uid, gid)
781
Christian Heimesfaf2f632008-01-06 16:59:19 +0000782 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Georg Brandl116aa622007-08-15 14:28:22 +0000783 function will not follow symbolic links. Availability: Macintosh, Unix.
784
Georg Brandl116aa622007-08-15 14:28:22 +0000785
786.. function:: link(src, dst)
787
788 Create a hard link pointing to *src* named *dst*. Availability: Macintosh, Unix.
789
790
791.. function:: listdir(path)
792
793 Return a list containing the names of the entries in the directory. The list is
794 in arbitrary order. It does not include the special entries ``'.'`` and
795 ``'..'`` even if they are present in the directory. Availability: Macintosh,
796 Unix, Windows.
797
Georg Brandl55ac8f02007-09-01 13:51:09 +0000798 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
799 a list of Unicode objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000800
801
802.. function:: lstat(path)
803
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000804 Like :func:`stat`, but do not follow symbolic links. This is an alias for
805 :func:`stat` on platforms that do not support symbolic links, such as
806 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808
809.. function:: mkfifo(path[, mode])
810
Georg Brandlf4a41232008-05-26 17:55:52 +0000811 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The
812 default *mode* is ``0o666`` (octal). The current umask value is first masked
813 out from the mode. Availability: Macintosh, Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000814
815 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
816 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
817 rendezvous between "client" and "server" type processes: the server opens the
818 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
819 doesn't open the FIFO --- it just creates the rendezvous point.
820
821
Georg Brandlf4a41232008-05-26 17:55:52 +0000822.. function:: mknod(filename[, mode=0o600, device])
Georg Brandl116aa622007-08-15 14:28:22 +0000823
824 Create a filesystem node (file, device special file or named pipe) named
825 *filename*. *mode* specifies both the permissions to use and the type of node to
826 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
827 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
828 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
829 For ``stat.S_IFCHR`` and
830 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
831 :func:`os.makedev`), otherwise it is ignored.
832
Georg Brandl116aa622007-08-15 14:28:22 +0000833
834.. function:: major(device)
835
Christian Heimesfaf2f632008-01-06 16:59:19 +0000836 Extract the device major number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +0000837 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
838
Georg Brandl116aa622007-08-15 14:28:22 +0000839
840.. function:: minor(device)
841
Christian Heimesfaf2f632008-01-06 16:59:19 +0000842 Extract the device minor number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +0000843 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
844
Georg Brandl116aa622007-08-15 14:28:22 +0000845
846.. function:: makedev(major, minor)
847
Christian Heimesfaf2f632008-01-06 16:59:19 +0000848 Compose a raw device number from the major and minor device numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000849
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851.. function:: mkdir(path[, mode])
852
Georg Brandlf4a41232008-05-26 17:55:52 +0000853 Create a directory named *path* with numeric mode *mode*. The default *mode*
854 is ``0o777`` (octal). On some systems, *mode* is ignored. Where it is used,
855 the current umask value is first masked out. Availability: Macintosh, Unix,
856 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000857
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000858 It is also possible to create temporary directories; see the
859 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
860
Georg Brandl116aa622007-08-15 14:28:22 +0000861
862.. function:: makedirs(path[, mode])
863
864 .. index::
865 single: directory; creating
866 single: UNC paths; and os.makedirs()
867
868 Recursive directory creation function. Like :func:`mkdir`, but makes all
Georg Brandlf4a41232008-05-26 17:55:52 +0000869 intermediate-level directories needed to contain the leaf directory. Throws
870 an :exc:`error` exception if the leaf directory already exists or cannot be
871 created. The default *mode* is ``0o777`` (octal). On some systems, *mode*
872 is ignored. Where it is used, the current umask value is first masked out.
Georg Brandl116aa622007-08-15 14:28:22 +0000873
874 .. note::
875
876 :func:`makedirs` will become confused if the path elements to create include
Christian Heimesfaf2f632008-01-06 16:59:19 +0000877 :data:`os.pardir`.
Georg Brandl116aa622007-08-15 14:28:22 +0000878
Georg Brandl55ac8f02007-09-01 13:51:09 +0000879 This function handles UNC paths correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000880
881
882.. function:: pathconf(path, name)
883
884 Return system configuration information relevant to a named file. *name*
885 specifies the configuration value to retrieve; it may be a string which is the
886 name of a defined system value; these names are specified in a number of
887 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
888 additional names as well. The names known to the host operating system are
889 given in the ``pathconf_names`` dictionary. For configuration variables not
890 included in that mapping, passing an integer for *name* is also accepted.
891 Availability: Macintosh, Unix.
892
893 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
894 specific value for *name* is not supported by the host system, even if it is
895 included in ``pathconf_names``, an :exc:`OSError` is raised with
896 :const:`errno.EINVAL` for the error number.
897
898
899.. data:: pathconf_names
900
901 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
902 the integer values defined for those names by the host operating system. This
903 can be used to determine the set of names known to the system. Availability:
904 Macintosh, Unix.
905
906
907.. function:: readlink(path)
908
909 Return a string representing the path to which the symbolic link points. The
910 result may be either an absolute or relative pathname; if it is relative, it may
911 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
912 result)``.
913
Georg Brandl55ac8f02007-09-01 13:51:09 +0000914 If the *path* is a Unicode object, the result will also be a Unicode object.
Georg Brandl116aa622007-08-15 14:28:22 +0000915
916 Availability: Macintosh, Unix.
917
918
919.. function:: remove(path)
920
921 Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
922 :func:`rmdir` below to remove a directory. This is identical to the
923 :func:`unlink` function documented below. On Windows, attempting to remove a
924 file that is in use causes an exception to be raised; on Unix, the directory
925 entry is removed but the storage allocated to the file is not made available
926 until the original file is no longer in use. Availability: Macintosh, Unix,
927 Windows.
928
929
930.. function:: removedirs(path)
931
932 .. index:: single: directory; deleting
933
Christian Heimesfaf2f632008-01-06 16:59:19 +0000934 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000935 leaf directory is successfully removed, :func:`removedirs` tries to
936 successively remove every parent directory mentioned in *path* until an error
937 is raised (which is ignored, because it generally means that a parent directory
938 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
939 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
940 they are empty. Raises :exc:`OSError` if the leaf directory could not be
941 successfully removed.
942
Georg Brandl116aa622007-08-15 14:28:22 +0000943
944.. function:: rename(src, dst)
945
946 Rename the file or directory *src* to *dst*. If *dst* is a directory,
947 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Christian Heimesfaf2f632008-01-06 16:59:19 +0000948 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl116aa622007-08-15 14:28:22 +0000949 Unix flavors if *src* and *dst* are on different filesystems. If successful,
950 the renaming will be an atomic operation (this is a POSIX requirement). On
951 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
952 file; there may be no way to implement an atomic rename when *dst* names an
953 existing file. Availability: Macintosh, Unix, Windows.
954
955
956.. function:: renames(old, new)
957
958 Recursive directory or file renaming function. Works like :func:`rename`, except
959 creation of any intermediate directories needed to make the new pathname good is
960 attempted first. After the rename, directories corresponding to rightmost path
961 segments of the old name will be pruned away using :func:`removedirs`.
962
Georg Brandl116aa622007-08-15 14:28:22 +0000963 .. note::
964
965 This function can fail with the new directory structure made if you lack
966 permissions needed to remove the leaf directory or file.
967
968
969.. function:: rmdir(path)
970
971 Remove the directory *path*. Availability: Macintosh, Unix, Windows.
972
973
974.. function:: stat(path)
975
976 Perform a :cfunc:`stat` system call on the given path. The return value is an
977 object whose attributes correspond to the members of the :ctype:`stat`
978 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
979 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
Christian Heimesfaf2f632008-01-06 16:59:19 +0000980 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
Georg Brandl116aa622007-08-15 14:28:22 +0000981 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
982 access), :attr:`st_mtime` (time of most recent content modification),
983 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
984 Unix, or the time of creation on Windows)::
985
986 >>> import os
987 >>> statinfo = os.stat('somefile.txt')
988 >>> statinfo
989 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
990 >>> statinfo.st_size
991 926L
992 >>>
993
Georg Brandl116aa622007-08-15 14:28:22 +0000994
995 On some Unix systems (such as Linux), the following attributes may also be
996 available: :attr:`st_blocks` (number of blocks allocated for file),
997 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
998 inode device). :attr:`st_flags` (user defined flags for file).
999
1000 On other Unix systems (such as FreeBSD), the following attributes may be
1001 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1002 (file generation number), :attr:`st_birthtime` (time of file creation).
1003
1004 On Mac OS systems, the following attributes may also be available:
1005 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1006
Georg Brandl116aa622007-08-15 14:28:22 +00001007 .. index:: module: stat
1008
1009 For backward compatibility, the return value of :func:`stat` is also accessible
1010 as a tuple of at least 10 integers giving the most important (and portable)
1011 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1012 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1013 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1014 :attr:`st_ctime`. More items may be added at the end by some implementations.
1015 The standard module :mod:`stat` defines functions and constants that are useful
1016 for extracting information from a :ctype:`stat` structure. (On Windows, some
1017 items are filled with dummy values.)
1018
1019 .. note::
1020
1021 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1022 :attr:`st_ctime` members depends on the operating system and the file system.
1023 For example, on Windows systems using the FAT or FAT32 file systems,
1024 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1025 resolution. See your operating system documentation for details.
1026
1027 Availability: Macintosh, Unix, Windows.
1028
Georg Brandl116aa622007-08-15 14:28:22 +00001029
1030.. function:: stat_float_times([newvalue])
1031
1032 Determine whether :class:`stat_result` represents time stamps as float objects.
1033 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1034 ``False``, future calls return ints. If *newvalue* is omitted, return the
1035 current setting.
1036
1037 For compatibility with older Python versions, accessing :class:`stat_result` as
1038 a tuple always returns integers.
1039
Georg Brandl55ac8f02007-09-01 13:51:09 +00001040 Python now returns float values by default. Applications which do not work
1041 correctly with floating point time stamps can use this function to restore the
1042 old behaviour.
Georg Brandl116aa622007-08-15 14:28:22 +00001043
1044 The resolution of the timestamps (that is the smallest possible fraction)
1045 depends on the system. Some systems only support second resolution; on these
1046 systems, the fraction will always be zero.
1047
1048 It is recommended that this setting is only changed at program startup time in
1049 the *__main__* module; libraries should never change this setting. If an
1050 application uses a library that works incorrectly if floating point time stamps
1051 are processed, this application should turn the feature off until the library
1052 has been corrected.
1053
1054
1055.. function:: statvfs(path)
1056
1057 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1058 an object whose attributes describe the filesystem on the given path, and
1059 correspond to the members of the :ctype:`statvfs` structure, namely:
1060 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1061 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1062 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1063
Georg Brandl116aa622007-08-15 14:28:22 +00001064
1065.. function:: symlink(src, dst)
1066
1067 Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
1068
1069
Georg Brandl116aa622007-08-15 14:28:22 +00001070.. function:: unlink(path)
1071
1072 Remove the file *path*. This is the same function as :func:`remove`; the
1073 :func:`unlink` name is its traditional Unix name. Availability: Macintosh, Unix,
1074 Windows.
1075
1076
1077.. function:: utime(path, times)
1078
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00001079 Set the access and modified times of the file specified by *path*. If *times*
1080 is ``None``, then the file's access and modified times are set to the current
1081 time. (The effect is similar to running the Unix program :program:`touch` on
1082 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1083 ``(atime, mtime)`` which is used to set the access and modified times,
1084 respectively. Whether a directory can be given for *path* depends on whether
1085 the operating system implements directories as files (for example, Windows
1086 does not). Note that the exact times you set here may not be returned by a
1087 subsequent :func:`stat` call, depending on the resolution with which your
1088 operating system records access and modification times; see :func:`stat`.
Georg Brandl116aa622007-08-15 14:28:22 +00001089
Georg Brandl116aa622007-08-15 14:28:22 +00001090 Availability: Macintosh, Unix, Windows.
1091
1092
1093.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1094
1095 .. index::
1096 single: directory; walking
1097 single: directory; traversal
1098
Christian Heimesfaf2f632008-01-06 16:59:19 +00001099 Generate the file names in a directory tree by walking the tree
1100 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl116aa622007-08-15 14:28:22 +00001101 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1102 filenames)``.
1103
1104 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1105 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1106 *filenames* is a list of the names of the non-directory files in *dirpath*.
1107 Note that the names in the lists contain no path components. To get a full path
1108 (which begins with *top*) to a file or directory in *dirpath*, do
1109 ``os.path.join(dirpath, name)``.
1110
Christian Heimesfaf2f632008-01-06 16:59:19 +00001111 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001112 directory is generated before the triples for any of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001113 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001114 directory is generated after the triples for all of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001115 (directories are generated bottom-up).
Georg Brandl116aa622007-08-15 14:28:22 +00001116
Christian Heimesfaf2f632008-01-06 16:59:19 +00001117 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl116aa622007-08-15 14:28:22 +00001118 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1119 recurse into the subdirectories whose names remain in *dirnames*; this can be
1120 used to prune the search, impose a specific order of visiting, or even to inform
1121 :func:`walk` about directories the caller creates or renames before it resumes
Christian Heimesfaf2f632008-01-06 16:59:19 +00001122 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl116aa622007-08-15 14:28:22 +00001123 ineffective, because in bottom-up mode the directories in *dirnames* are
1124 generated before *dirpath* itself is generated.
1125
Christian Heimesfaf2f632008-01-06 16:59:19 +00001126 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl116aa622007-08-15 14:28:22 +00001127 argument *onerror* is specified, it should be a function; it will be called with
1128 one argument, an :exc:`OSError` instance. It can report the error to continue
1129 with the walk, or raise the exception to abort the walk. Note that the filename
1130 is available as the ``filename`` attribute of the exception object.
1131
1132 By default, :func:`walk` will not walk down into symbolic links that resolve to
Christian Heimesfaf2f632008-01-06 16:59:19 +00001133 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl116aa622007-08-15 14:28:22 +00001134 symlinks, on systems that support them.
1135
Georg Brandl116aa622007-08-15 14:28:22 +00001136 .. note::
1137
Christian Heimesfaf2f632008-01-06 16:59:19 +00001138 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl116aa622007-08-15 14:28:22 +00001139 link points to a parent directory of itself. :func:`walk` does not keep track of
1140 the directories it visited already.
1141
1142 .. note::
1143
1144 If you pass a relative pathname, don't change the current working directory
1145 between resumptions of :func:`walk`. :func:`walk` never changes the current
1146 directory, and assumes that its caller doesn't either.
1147
1148 This example displays the number of bytes taken by non-directory files in each
1149 directory under the starting directory, except that it doesn't look under any
1150 CVS subdirectory::
1151
1152 import os
1153 from os.path import join, getsize
1154 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001155 print(root, "consumes", end=" ")
1156 print(sum(getsize(join(root, name)) for name in files), end=" ")
1157 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00001158 if 'CVS' in dirs:
1159 dirs.remove('CVS') # don't visit CVS directories
1160
Christian Heimesfaf2f632008-01-06 16:59:19 +00001161 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl116aa622007-08-15 14:28:22 +00001162 doesn't allow deleting a directory before the directory is empty::
1163
Christian Heimesfaf2f632008-01-06 16:59:19 +00001164 # Delete everything reachable from the directory named in "top",
Georg Brandl116aa622007-08-15 14:28:22 +00001165 # assuming there are no symbolic links.
1166 # CAUTION: This is dangerous! For example, if top == '/', it
1167 # could delete all your disk files.
1168 import os
1169 for root, dirs, files in os.walk(top, topdown=False):
1170 for name in files:
1171 os.remove(os.path.join(root, name))
1172 for name in dirs:
1173 os.rmdir(os.path.join(root, name))
1174
Georg Brandl116aa622007-08-15 14:28:22 +00001175
1176.. _os-process:
1177
1178Process Management
1179------------------
1180
1181These functions may be used to create and manage processes.
1182
1183The various :func:`exec\*` functions take a list of arguments for the new
1184program loaded into the process. In each case, the first of these arguments is
1185passed to the new program as its own name rather than as an argument a user may
1186have typed on a command line. For the C programmer, this is the ``argv[0]``
1187passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1188['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1189to be ignored.
1190
1191
1192.. function:: abort()
1193
1194 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1195 behavior is to produce a core dump; on Windows, the process immediately returns
1196 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1197 to register a handler for :const:`SIGABRT` will behave differently.
1198 Availability: Macintosh, Unix, Windows.
1199
1200
1201.. function:: execl(path, arg0, arg1, ...)
1202 execle(path, arg0, arg1, ..., env)
1203 execlp(file, arg0, arg1, ...)
1204 execlpe(file, arg0, arg1, ..., env)
1205 execv(path, args)
1206 execve(path, args, env)
1207 execvp(file, args)
1208 execvpe(file, args, env)
1209
1210 These functions all execute a new program, replacing the current process; they
1211 do not return. On Unix, the new executable is loaded into the current process,
Christian Heimesfaf2f632008-01-06 16:59:19 +00001212 and will have the same process id as the caller. Errors will be reported as
Georg Brandl116aa622007-08-15 14:28:22 +00001213 :exc:`OSError` exceptions.
1214
Christian Heimesfaf2f632008-01-06 16:59:19 +00001215 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1216 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001217 to work with if the number of parameters is fixed when the code is written; the
1218 individual parameters simply become additional parameters to the :func:`execl\*`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001219 functions. The "v" variants are good when the number of parameters is
Georg Brandl116aa622007-08-15 14:28:22 +00001220 variable, with the arguments being passed in a list or tuple as the *args*
1221 parameter. In either case, the arguments to the child process should start with
1222 the name of the command being run, but this is not enforced.
1223
Christian Heimesfaf2f632008-01-06 16:59:19 +00001224 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001225 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1226 :envvar:`PATH` environment variable to locate the program *file*. When the
1227 environment is being replaced (using one of the :func:`exec\*e` variants,
1228 discussed in the next paragraph), the new environment is used as the source of
1229 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1230 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1231 locate the executable; *path* must contain an appropriate absolute or relative
1232 path.
1233
1234 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Christian Heimesfaf2f632008-01-06 16:59:19 +00001235 that these all end in "e"), the *env* parameter must be a mapping which is
Christian Heimesa342c012008-04-20 21:01:16 +00001236 used to define the environment variables for the new process (these are used
1237 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl116aa622007-08-15 14:28:22 +00001238 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1239 inherit the environment of the current process. Availability: Macintosh, Unix,
1240 Windows.
1241
1242
1243.. function:: _exit(n)
1244
1245 Exit to the system with status *n*, without calling cleanup handlers, flushing
1246 stdio buffers, etc. Availability: Macintosh, Unix, Windows.
1247
1248 .. note::
1249
1250 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1251 be used in the child process after a :func:`fork`.
1252
Christian Heimesfaf2f632008-01-06 16:59:19 +00001253The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl116aa622007-08-15 14:28:22 +00001254although they are not required. These are typically used for system programs
1255written in Python, such as a mail server's external command delivery program.
1256
1257.. note::
1258
1259 Some of these may not be available on all Unix platforms, since there is some
1260 variation. These constants are defined where they are defined by the underlying
1261 platform.
1262
1263
1264.. data:: EX_OK
1265
1266 Exit code that means no error occurred. Availability: Macintosh, Unix.
1267
Georg Brandl116aa622007-08-15 14:28:22 +00001268
1269.. data:: EX_USAGE
1270
1271 Exit code that means the command was used incorrectly, such as when the wrong
1272 number of arguments are given. Availability: Macintosh, Unix.
1273
Georg Brandl116aa622007-08-15 14:28:22 +00001274
1275.. data:: EX_DATAERR
1276
1277 Exit code that means the input data was incorrect. Availability: Macintosh,
1278 Unix.
1279
Georg Brandl116aa622007-08-15 14:28:22 +00001280
1281.. data:: EX_NOINPUT
1282
1283 Exit code that means an input file did not exist or was not readable.
1284 Availability: Macintosh, Unix.
1285
Georg Brandl116aa622007-08-15 14:28:22 +00001286
1287.. data:: EX_NOUSER
1288
1289 Exit code that means a specified user did not exist. Availability: Macintosh,
1290 Unix.
1291
Georg Brandl116aa622007-08-15 14:28:22 +00001292
1293.. data:: EX_NOHOST
1294
1295 Exit code that means a specified host did not exist. Availability: Macintosh,
1296 Unix.
1297
Georg Brandl116aa622007-08-15 14:28:22 +00001298
1299.. data:: EX_UNAVAILABLE
1300
1301 Exit code that means that a required service is unavailable. Availability:
1302 Macintosh, Unix.
1303
Georg Brandl116aa622007-08-15 14:28:22 +00001304
1305.. data:: EX_SOFTWARE
1306
1307 Exit code that means an internal software error was detected. Availability:
1308 Macintosh, Unix.
1309
Georg Brandl116aa622007-08-15 14:28:22 +00001310
1311.. data:: EX_OSERR
1312
1313 Exit code that means an operating system error was detected, such as the
1314 inability to fork or create a pipe. Availability: Macintosh, Unix.
1315
Georg Brandl116aa622007-08-15 14:28:22 +00001316
1317.. data:: EX_OSFILE
1318
1319 Exit code that means some system file did not exist, could not be opened, or had
1320 some other kind of error. Availability: Macintosh, Unix.
1321
Georg Brandl116aa622007-08-15 14:28:22 +00001322
1323.. data:: EX_CANTCREAT
1324
1325 Exit code that means a user specified output file could not be created.
1326 Availability: Macintosh, Unix.
1327
Georg Brandl116aa622007-08-15 14:28:22 +00001328
1329.. data:: EX_IOERR
1330
1331 Exit code that means that an error occurred while doing I/O on some file.
1332 Availability: Macintosh, Unix.
1333
Georg Brandl116aa622007-08-15 14:28:22 +00001334
1335.. data:: EX_TEMPFAIL
1336
1337 Exit code that means a temporary failure occurred. This indicates something
1338 that may not really be an error, such as a network connection that couldn't be
1339 made during a retryable operation. Availability: Macintosh, Unix.
1340
Georg Brandl116aa622007-08-15 14:28:22 +00001341
1342.. data:: EX_PROTOCOL
1343
1344 Exit code that means that a protocol exchange was illegal, invalid, or not
1345 understood. Availability: Macintosh, Unix.
1346
Georg Brandl116aa622007-08-15 14:28:22 +00001347
1348.. data:: EX_NOPERM
1349
1350 Exit code that means that there were insufficient permissions to perform the
1351 operation (but not intended for file system problems). Availability: Macintosh,
1352 Unix.
1353
Georg Brandl116aa622007-08-15 14:28:22 +00001354
1355.. data:: EX_CONFIG
1356
1357 Exit code that means that some kind of configuration error occurred.
1358 Availability: Macintosh, Unix.
1359
Georg Brandl116aa622007-08-15 14:28:22 +00001360
1361.. data:: EX_NOTFOUND
1362
1363 Exit code that means something like "an entry was not found". Availability:
1364 Macintosh, Unix.
1365
Georg Brandl116aa622007-08-15 14:28:22 +00001366
1367.. function:: fork()
1368
Christian Heimesfaf2f632008-01-06 16:59:19 +00001369 Fork a child process. Return ``0`` in the child and the child's process id in the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001370 parent. If an error occurs :exc:`OSError` is raised.
1371 Availability: Macintosh, Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001372
1373
1374.. function:: forkpty()
1375
1376 Fork a child process, using a new pseudo-terminal as the child's controlling
1377 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1378 new child's process id in the parent, and *fd* is the file descriptor of the
1379 master end of the pseudo-terminal. For a more portable approach, use the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001380 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
1381 Availability: Macintosh, some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001382
1383
1384.. function:: kill(pid, sig)
1385
1386 .. index::
1387 single: process; killing
1388 single: process; signalling
1389
1390 Send signal *sig* to the process *pid*. Constants for the specific signals
1391 available on the host platform are defined in the :mod:`signal` module.
1392 Availability: Macintosh, Unix.
1393
1394
1395.. function:: killpg(pgid, sig)
1396
1397 .. index::
1398 single: process; killing
1399 single: process; signalling
1400
1401 Send the signal *sig* to the process group *pgid*. Availability: Macintosh,
1402 Unix.
1403
Georg Brandl116aa622007-08-15 14:28:22 +00001404
1405.. function:: nice(increment)
1406
1407 Add *increment* to the process's "niceness". Return the new niceness.
1408 Availability: Macintosh, Unix.
1409
1410
1411.. function:: plock(op)
1412
1413 Lock program segments into memory. The value of *op* (defined in
1414 ``<sys/lock.h>``) determines which segments are locked. Availability: Macintosh,
1415 Unix.
1416
1417
1418.. function:: popen(...)
1419 :noindex:
1420
1421 Run child processes, returning opened pipes for communications. These functions
1422 are described in section :ref:`os-newstreams`.
1423
1424
1425.. function:: spawnl(mode, path, ...)
1426 spawnle(mode, path, ..., env)
1427 spawnlp(mode, file, ...)
1428 spawnlpe(mode, file, ..., env)
1429 spawnv(mode, path, args)
1430 spawnve(mode, path, args, env)
1431 spawnvp(mode, file, args)
1432 spawnvpe(mode, file, args, env)
1433
1434 Execute the program *path* in a new process.
1435
1436 (Note that the :mod:`subprocess` module provides more powerful facilities for
1437 spawning new processes and retrieving their results; using that module is
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001438 preferable to using these functions. Check specially the *Replacing Older
1439 Functions with the subprocess Module* section in that documentation page.)
Georg Brandl116aa622007-08-15 14:28:22 +00001440
Christian Heimesfaf2f632008-01-06 16:59:19 +00001441 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl116aa622007-08-15 14:28:22 +00001442 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1443 exits normally, or ``-signal``, where *signal* is the signal that killed the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001444 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl116aa622007-08-15 14:28:22 +00001445 be used with the :func:`waitpid` function.
1446
Christian Heimesfaf2f632008-01-06 16:59:19 +00001447 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1448 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001449 to work with if the number of parameters is fixed when the code is written; the
1450 individual parameters simply become additional parameters to the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001451 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl116aa622007-08-15 14:28:22 +00001452 parameters is variable, with the arguments being passed in a list or tuple as
1453 the *args* parameter. In either case, the arguments to the child process must
1454 start with the name of the command being run.
1455
Christian Heimesfaf2f632008-01-06 16:59:19 +00001456 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001457 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1458 :envvar:`PATH` environment variable to locate the program *file*. When the
1459 environment is being replaced (using one of the :func:`spawn\*e` variants,
1460 discussed in the next paragraph), the new environment is used as the source of
1461 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1462 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1463 :envvar:`PATH` variable to locate the executable; *path* must contain an
1464 appropriate absolute or relative path.
1465
1466 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001467 (note that these all end in "e"), the *env* parameter must be a mapping
Christian Heimesa342c012008-04-20 21:01:16 +00001468 which is used to define the environment variables for the new process (they are
1469 used instead of the current process' environment); the functions
Georg Brandl116aa622007-08-15 14:28:22 +00001470 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1471 the new process to inherit the environment of the current process.
1472
1473 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1474 equivalent::
1475
1476 import os
1477 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1478
1479 L = ['cp', 'index.html', '/dev/null']
1480 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1481
1482 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1483 and :func:`spawnvpe` are not available on Windows.
1484
Georg Brandl116aa622007-08-15 14:28:22 +00001485
1486.. data:: P_NOWAIT
1487 P_NOWAITO
1488
1489 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1490 functions. If either of these values is given, the :func:`spawn\*` functions
Christian Heimesfaf2f632008-01-06 16:59:19 +00001491 will return as soon as the new process has been created, with the process id as
Georg Brandl116aa622007-08-15 14:28:22 +00001492 the return value. Availability: Macintosh, Unix, Windows.
1493
Georg Brandl116aa622007-08-15 14:28:22 +00001494
1495.. data:: P_WAIT
1496
1497 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1498 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1499 return until the new process has run to completion and will return the exit code
1500 of the process the run is successful, or ``-signal`` if a signal kills the
1501 process. Availability: Macintosh, Unix, Windows.
1502
Georg Brandl116aa622007-08-15 14:28:22 +00001503
1504.. data:: P_DETACH
1505 P_OVERLAY
1506
1507 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1508 functions. These are less portable than those listed above. :const:`P_DETACH`
1509 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1510 console of the calling process. If :const:`P_OVERLAY` is used, the current
1511 process will be replaced; the :func:`spawn\*` function will not return.
1512 Availability: Windows.
1513
Georg Brandl116aa622007-08-15 14:28:22 +00001514
1515.. function:: startfile(path[, operation])
1516
1517 Start a file with its associated application.
1518
1519 When *operation* is not specified or ``'open'``, this acts like double-clicking
1520 the file in Windows Explorer, or giving the file name as an argument to the
1521 :program:`start` command from the interactive command shell: the file is opened
1522 with whatever application (if any) its extension is associated.
1523
1524 When another *operation* is given, it must be a "command verb" that specifies
1525 what should be done with the file. Common verbs documented by Microsoft are
1526 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1527 ``'find'`` (to be used on directories).
1528
1529 :func:`startfile` returns as soon as the associated application is launched.
1530 There is no option to wait for the application to close, and no way to retrieve
1531 the application's exit status. The *path* parameter is relative to the current
1532 directory. If you want to use an absolute path, make sure the first character
1533 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1534 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1535 the path is properly encoded for Win32. Availability: Windows.
1536
Georg Brandl116aa622007-08-15 14:28:22 +00001537
1538.. function:: system(command)
1539
1540 Execute the command (a string) in a subshell. This is implemented by calling
1541 the Standard C function :cfunc:`system`, and has the same limitations. Changes
Christian Heimesfaf2f632008-01-06 16:59:19 +00001542 to :data:`os.environ`, :data:`sys.stdin`, etc. are not reflected in the
1543 environment of the executed command.
Georg Brandl116aa622007-08-15 14:28:22 +00001544
1545 On Unix, the return value is the exit status of the process encoded in the
1546 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1547 of the return value of the C :cfunc:`system` function, so the return value of
1548 the Python function is system-dependent.
1549
1550 On Windows, the return value is that returned by the system shell after running
1551 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1552 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1553 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1554 the command run; on systems using a non-native shell, consult your shell
1555 documentation.
1556
1557 Availability: Macintosh, Unix, Windows.
1558
1559 The :mod:`subprocess` module provides more powerful facilities for spawning new
1560 processes and retrieving their results; using that module is preferable to using
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001561 this function. Use the :mod:`subprocess` module. Check especially the
1562 :ref:`subprocess-replacements` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001563
1564
1565.. function:: times()
1566
1567 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1568 other) times, in seconds. The items are: user time, system time, children's
1569 user time, children's system time, and elapsed real time since a fixed point in
1570 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
1571 corresponding Windows Platform API documentation. Availability: Macintosh, Unix,
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001572 Windows. On Windows, only the first two items are filled, the others are zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001573
1574
1575.. function:: wait()
1576
1577 Wait for completion of a child process, and return a tuple containing its pid
1578 and exit status indication: a 16-bit number, whose low byte is the signal number
1579 that killed the process, and whose high byte is the exit status (if the signal
1580 number is zero); the high bit of the low byte is set if a core file was
1581 produced. Availability: Macintosh, Unix.
1582
1583
1584.. function:: waitpid(pid, options)
1585
1586 The details of this function differ on Unix and Windows.
1587
1588 On Unix: Wait for completion of a child process given by process id *pid*, and
1589 return a tuple containing its process id and exit status indication (encoded as
1590 for :func:`wait`). The semantics of the call are affected by the value of the
1591 integer *options*, which should be ``0`` for normal operation.
1592
1593 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1594 that specific process. If *pid* is ``0``, the request is for the status of any
1595 child in the process group of the current process. If *pid* is ``-1``, the
1596 request pertains to any child of the current process. If *pid* is less than
1597 ``-1``, status is requested for any process in the process group ``-pid`` (the
1598 absolute value of *pid*).
1599
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00001600 An :exc:`OSError` is raised with the value of errno when the syscall
1601 returns -1.
1602
Georg Brandl116aa622007-08-15 14:28:22 +00001603 On Windows: Wait for completion of a process given by process handle *pid*, and
1604 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1605 (shifting makes cross-platform use of the function easier). A *pid* less than or
1606 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1607 value of integer *options* has no effect. *pid* can refer to any process whose
1608 id is known, not necessarily a child process. The :func:`spawn` functions called
1609 with :const:`P_NOWAIT` return suitable process handles.
1610
1611
1612.. function:: wait3([options])
1613
1614 Similar to :func:`waitpid`, except no process id argument is given and a
1615 3-element tuple containing the child's process id, exit status indication, and
1616 resource usage information is returned. Refer to :mod:`resource`.\
1617 :func:`getrusage` for details on resource usage information. The option
1618 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1619 Availability: Unix.
1620
Georg Brandl116aa622007-08-15 14:28:22 +00001621
1622.. function:: wait4(pid, options)
1623
1624 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1625 process id, exit status indication, and resource usage information is returned.
1626 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1627 information. The arguments to :func:`wait4` are the same as those provided to
1628 :func:`waitpid`. Availability: Unix.
1629
Georg Brandl116aa622007-08-15 14:28:22 +00001630
1631.. data:: WNOHANG
1632
1633 The option for :func:`waitpid` to return immediately if no child process status
1634 is available immediately. The function returns ``(0, 0)`` in this case.
1635 Availability: Macintosh, Unix.
1636
1637
1638.. data:: WCONTINUED
1639
1640 This option causes child processes to be reported if they have been continued
1641 from a job control stop since their status was last reported. Availability: Some
1642 Unix systems.
1643
Georg Brandl116aa622007-08-15 14:28:22 +00001644
1645.. data:: WUNTRACED
1646
1647 This option causes child processes to be reported if they have been stopped but
1648 their current state has not been reported since they were stopped. Availability:
1649 Macintosh, Unix.
1650
Georg Brandl116aa622007-08-15 14:28:22 +00001651
1652The following functions take a process status code as returned by
1653:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1654used to determine the disposition of a process.
1655
Georg Brandl116aa622007-08-15 14:28:22 +00001656.. function:: WCOREDUMP(status)
1657
Christian Heimesfaf2f632008-01-06 16:59:19 +00001658 Return ``True`` if a core dump was generated for the process, otherwise
1659 return ``False``. Availability: Macintosh, Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001660
Georg Brandl116aa622007-08-15 14:28:22 +00001661
1662.. function:: WIFCONTINUED(status)
1663
Christian Heimesfaf2f632008-01-06 16:59:19 +00001664 Return ``True`` if the process has been continued from a job control stop,
1665 otherwise return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001666
Georg Brandl116aa622007-08-15 14:28:22 +00001667
1668.. function:: WIFSTOPPED(status)
1669
Christian Heimesfaf2f632008-01-06 16:59:19 +00001670 Return ``True`` if the process has been stopped, otherwise return
Georg Brandl116aa622007-08-15 14:28:22 +00001671 ``False``. Availability: Unix.
1672
1673
1674.. function:: WIFSIGNALED(status)
1675
Christian Heimesfaf2f632008-01-06 16:59:19 +00001676 Return ``True`` if the process exited due to a signal, otherwise return
Georg Brandl116aa622007-08-15 14:28:22 +00001677 ``False``. Availability: Macintosh, Unix.
1678
1679
1680.. function:: WIFEXITED(status)
1681
Christian Heimesfaf2f632008-01-06 16:59:19 +00001682 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
1683 otherwise return ``False``. Availability: Macintosh, Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001684
1685
1686.. function:: WEXITSTATUS(status)
1687
1688 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1689 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
1690 Availability: Macintosh, Unix.
1691
1692
1693.. function:: WSTOPSIG(status)
1694
1695 Return the signal which caused the process to stop. Availability: Macintosh,
1696 Unix.
1697
1698
1699.. function:: WTERMSIG(status)
1700
1701 Return the signal which caused the process to exit. Availability: Macintosh,
1702 Unix.
1703
1704
1705.. _os-path:
1706
1707Miscellaneous System Information
1708--------------------------------
1709
1710
1711.. function:: confstr(name)
1712
1713 Return string-valued system configuration values. *name* specifies the
1714 configuration value to retrieve; it may be a string which is the name of a
1715 defined system value; these names are specified in a number of standards (POSIX,
1716 Unix 95, Unix 98, and others). Some platforms define additional names as well.
1717 The names known to the host operating system are given as the keys of the
1718 ``confstr_names`` dictionary. For configuration variables not included in that
1719 mapping, passing an integer for *name* is also accepted. Availability:
1720 Macintosh, Unix.
1721
1722 If the configuration value specified by *name* isn't defined, ``None`` is
1723 returned.
1724
1725 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1726 specific value for *name* is not supported by the host system, even if it is
1727 included in ``confstr_names``, an :exc:`OSError` is raised with
1728 :const:`errno.EINVAL` for the error number.
1729
1730
1731.. data:: confstr_names
1732
1733 Dictionary mapping names accepted by :func:`confstr` to the integer values
1734 defined for those names by the host operating system. This can be used to
1735 determine the set of names known to the system. Availability: Macintosh, Unix.
1736
1737
1738.. function:: getloadavg()
1739
Christian Heimesa62da1d2008-01-12 19:39:10 +00001740 Return the number of processes in the system run queue averaged over the last
1741 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001742 unobtainable. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001743
Georg Brandl116aa622007-08-15 14:28:22 +00001744
1745.. function:: sysconf(name)
1746
1747 Return integer-valued system configuration values. If the configuration value
1748 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
1749 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
1750 provides information on the known names is given by ``sysconf_names``.
1751 Availability: Macintosh, Unix.
1752
1753
1754.. data:: sysconf_names
1755
1756 Dictionary mapping names accepted by :func:`sysconf` to the integer values
1757 defined for those names by the host operating system. This can be used to
1758 determine the set of names known to the system. Availability: Macintosh, Unix.
1759
Christian Heimesfaf2f632008-01-06 16:59:19 +00001760The following data values are used to support path manipulation operations. These
Georg Brandl116aa622007-08-15 14:28:22 +00001761are defined for all platforms.
1762
1763Higher-level operations on pathnames are defined in the :mod:`os.path` module.
1764
1765
1766.. data:: curdir
1767
1768 The constant string used by the operating system to refer to the current
1769 directory. For example: ``'.'`` for POSIX or ``':'`` for Mac OS 9. Also
1770 available via :mod:`os.path`.
1771
1772
1773.. data:: pardir
1774
1775 The constant string used by the operating system to refer to the parent
1776 directory. For example: ``'..'`` for POSIX or ``'::'`` for Mac OS 9. Also
1777 available via :mod:`os.path`.
1778
1779
1780.. data:: sep
1781
1782 The character used by the operating system to separate pathname components, for
1783 example, ``'/'`` for POSIX or ``':'`` for Mac OS 9. Note that knowing this is
1784 not sufficient to be able to parse or concatenate pathnames --- use
1785 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
1786 useful. Also available via :mod:`os.path`.
1787
1788
1789.. data:: altsep
1790
1791 An alternative character used by the operating system to separate pathname
1792 components, or ``None`` if only one separator character exists. This is set to
1793 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
1794 :mod:`os.path`.
1795
1796
1797.. data:: extsep
1798
1799 The character which separates the base filename from the extension; for example,
1800 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
1801
Georg Brandl116aa622007-08-15 14:28:22 +00001802
1803.. data:: pathsep
1804
1805 The character conventionally used by the operating system to separate search
1806 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
1807 Windows. Also available via :mod:`os.path`.
1808
1809
1810.. data:: defpath
1811
1812 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
1813 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
1814
1815
1816.. data:: linesep
1817
1818 The string used to separate (or, rather, terminate) lines on the current
1819 platform. This may be a single character, such as ``'\n'`` for POSIX or
1820 ``'\r'`` for Mac OS, or multiple characters, for example, ``'\r\n'`` for
1821 Windows. Do not use *os.linesep* as a line terminator when writing files opened
1822 in text mode (the default); use a single ``'\n'`` instead, on all platforms.
1823
1824
1825.. data:: devnull
1826
1827 The file path of the null device. For example: ``'/dev/null'`` for POSIX or
1828 ``'Dev:Nul'`` for Mac OS 9. Also available via :mod:`os.path`.
1829
Georg Brandl116aa622007-08-15 14:28:22 +00001830
1831.. _os-miscfunc:
1832
1833Miscellaneous Functions
1834-----------------------
1835
1836
1837.. function:: urandom(n)
1838
1839 Return a string of *n* random bytes suitable for cryptographic use.
1840
1841 This function returns random bytes from an OS-specific randomness source. The
1842 returned data should be unpredictable enough for cryptographic applications,
1843 though its exact quality depends on the OS implementation. On a UNIX-like
1844 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
1845 If a randomness source is not found, :exc:`NotImplementedError` will be raised.