blob: ee0cf48bc600c7abef76c057d6dcf5bdb4d668ec [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`os` --- Miscellaneous operating system interfaces
3=======================================================
4
5.. module:: os
6 :synopsis: Miscellaneous operating system interfaces.
7
8
9This module provides a more portable way of using operating system dependent
Christian Heimesfaf2f632008-01-06 16:59:19 +000010functionality than importing an operating system dependent built-in module like
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011:mod:`posix` or :mod:`nt`. If you just want to read or write a file see
12:func:`open`, if you want to manipulate paths, see the :mod:`os.path`
13module, and if you want to read all the lines in all the files on the
Guido van Rossum2cc30da2007-11-02 23:46:40 +000014command line see the :mod:`fileinput` module. For creating temporary
15files and directories see the :mod:`tempfile` module, and for high-level
16file and directory handling see the :mod:`shutil` module.
Georg Brandl116aa622007-08-15 14:28:22 +000017
18This module searches for an operating system dependent built-in module like
19:mod:`mac` or :mod:`posix` and exports the same functions and data as found
Christian Heimesfaf2f632008-01-06 16:59:19 +000020there. The design of all built-in operating system dependent modules of Python
Georg Brandl116aa622007-08-15 14:28:22 +000021is such that as long as the same functionality is available, it uses the same
22interface; for example, the function ``os.stat(path)`` returns stat information
23about *path* in the same format (which happens to have originated with the POSIX
24interface).
25
26Extensions peculiar to a particular operating system are also available through
27the :mod:`os` module, but using them is of course a threat to portability!
28
29Note that after the first time :mod:`os` is imported, there is *no* performance
30penalty in using functions from :mod:`os` instead of directly from the operating
31system dependent built-in module, so there should be *no* reason not to use
32:mod:`os`!
33
34The :mod:`os` module contains many functions and data values. The items below
35and in the following sub-sections are all available directly from the :mod:`os`
36module.
37
Georg Brandl116aa622007-08-15 14:28:22 +000038.. exception:: error
39
40 .. index:: module: errno
41
42 This exception is raised when a function returns a system-related error (not for
43 illegal argument types or other incidental errors). This is also known as the
44 built-in exception :exc:`OSError`. The accompanying value is a pair containing
45 the numeric error code from :cdata:`errno` and the corresponding string, as
46 would be printed by the C function :cfunc:`perror`. See the module
47 :mod:`errno`, which contains names for the error codes defined by the underlying
48 operating system.
49
50 When exceptions are classes, this exception carries two attributes,
51 :attr:`errno` and :attr:`strerror`. The first holds the value of the C
52 :cdata:`errno` variable, and the latter holds the corresponding error message
53 from :cfunc:`strerror`. For exceptions that involve a file system path (such as
54 :func:`chdir` or :func:`unlink`), the exception instance will contain a third
55 attribute, :attr:`filename`, which is the file name passed to the function.
56
57
58.. data:: name
59
60 The name of the operating system dependent module imported. The following names
61 have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``,
Skip Montanaro7a98be22007-08-16 14:35:24 +000062 ``'ce'``, ``'java'``.
Georg Brandl116aa622007-08-15 14:28:22 +000063
64
65.. data:: path
66
67 The corresponding operating system dependent standard module for pathname
68 operations, such as :mod:`posixpath` or :mod:`macpath`. Thus, given the proper
69 imports, ``os.path.split(file)`` is equivalent to but more portable than
70 ``posixpath.split(file)``. Note that this is also an importable module: it may
71 be imported directly as :mod:`os.path`.
72
73
74.. _os-procinfo:
75
76Process Parameters
77------------------
78
79These functions and data items provide information and operate on the current
80process and user.
81
82
83.. data:: environ
84
85 A mapping object representing the string environment. For example,
86 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
87 and is equivalent to ``getenv("HOME")`` in C.
88
89 This mapping is captured the first time the :mod:`os` module is imported,
90 typically during Python startup as part of processing :file:`site.py`. Changes
91 to the environment made after this time are not reflected in ``os.environ``,
92 except for changes made by modifying ``os.environ`` directly.
93
94 If the platform supports the :func:`putenv` function, this mapping may be used
95 to modify the environment as well as query the environment. :func:`putenv` will
96 be called automatically when the mapping is modified.
97
98 .. note::
99
100 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
101 to modify ``os.environ``.
102
103 .. note::
104
105 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause
106 memory leaks. Refer to the system documentation for :cfunc:`putenv`.
107
108 If :func:`putenv` is not provided, a modified copy of this mapping may be
109 passed to the appropriate process-creation functions to cause child processes
110 to use a modified environment.
111
Georg Brandl9afde1c2007-11-01 20:32:30 +0000112 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl116aa622007-08-15 14:28:22 +0000113 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl9afde1c2007-11-01 20:32:30 +0000114 automatically when an item is deleted from ``os.environ``, and when
115 one of the :meth:`pop` or :meth:`clear` methods is called.
116
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118.. function:: chdir(path)
119 fchdir(fd)
120 getcwd()
121 :noindex:
122
123 These functions are described in :ref:`os-file-dir`.
124
125
126.. function:: ctermid()
127
128 Return the filename corresponding to the controlling terminal of the process.
129 Availability: Unix.
130
131
132.. function:: getegid()
133
134 Return the effective group id of the current process. This corresponds to the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000135 "set id" bit on the file being executed in the current process. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000136 Unix.
137
138
139.. function:: geteuid()
140
141 .. index:: single: user; effective id
142
Christian Heimesfaf2f632008-01-06 16:59:19 +0000143 Return the current process's effective user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145
146.. function:: getgid()
147
148 .. index:: single: process; group
149
150 Return the real group id of the current process. Availability: Unix.
151
152
153.. function:: getgroups()
154
155 Return list of supplemental group ids associated with the current process.
156 Availability: Unix.
157
158
159.. function:: getlogin()
160
161 Return the name of the user logged in on the controlling terminal of the
162 process. For most purposes, it is more useful to use the environment variable
163 :envvar:`LOGNAME` to find out who the user is, or
164 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
Christian Heimesfaf2f632008-01-06 16:59:19 +0000165 effective user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000166
167
168.. function:: getpgid(pid)
169
170 Return the process group id of the process with process id *pid*. If *pid* is 0,
171 the process group id of the current process is returned. Availability: Unix.
172
Georg Brandl116aa622007-08-15 14:28:22 +0000173
174.. function:: getpgrp()
175
176 .. index:: single: process; group
177
178 Return the id of the current process group. Availability: Unix.
179
180
181.. function:: getpid()
182
183 .. index:: single: process; id
184
185 Return the current process id. Availability: Unix, Windows.
186
187
188.. function:: getppid()
189
190 .. index:: single: process; id of parent
191
192 Return the parent's process id. Availability: Unix.
193
194
195.. function:: getuid()
196
197 .. index:: single: user; id
198
Christian Heimesfaf2f632008-01-06 16:59:19 +0000199 Return the current process's user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201
202.. function:: getenv(varname[, value])
203
204 Return the value of the environment variable *varname* if it exists, or *value*
205 if it doesn't. *value* defaults to ``None``. Availability: most flavors of
206 Unix, Windows.
207
208
209.. function:: putenv(varname, value)
210
211 .. index:: single: environment variables; setting
212
213 Set the environment variable named *varname* to the string *value*. Such
214 changes to the environment affect subprocesses started with :func:`os.system`,
215 :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
216 Unix, Windows.
217
218 .. note::
219
220 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause
221 memory leaks. Refer to the system documentation for putenv.
222
223 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
224 automatically translated into corresponding calls to :func:`putenv`; however,
225 calls to :func:`putenv` don't update ``os.environ``, so it is actually
226 preferable to assign to items of ``os.environ``.
227
228
229.. function:: setegid(egid)
230
231 Set the current process's effective group id. Availability: Unix.
232
233
234.. function:: seteuid(euid)
235
236 Set the current process's effective user id. Availability: Unix.
237
238
239.. function:: setgid(gid)
240
241 Set the current process' group id. Availability: Unix.
242
243
244.. function:: setgroups(groups)
245
246 Set the list of supplemental group ids associated with the current process to
247 *groups*. *groups* must be a sequence, and each element must be an integer
Christian Heimesfaf2f632008-01-06 16:59:19 +0000248 identifying a group. This operation is typically available only to the superuser.
Georg Brandl116aa622007-08-15 14:28:22 +0000249 Availability: Unix.
250
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252.. function:: setpgrp()
253
Christian Heimesfaf2f632008-01-06 16:59:19 +0000254 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
Georg Brandl116aa622007-08-15 14:28:22 +0000255 which version is implemented (if any). See the Unix manual for the semantics.
256 Availability: Unix.
257
258
259.. function:: setpgid(pid, pgrp)
260
Christian Heimesfaf2f632008-01-06 16:59:19 +0000261 Call the system call :cfunc:`setpgid` to set the process group id of the
Georg Brandl116aa622007-08-15 14:28:22 +0000262 process with id *pid* to the process group with id *pgrp*. See the Unix manual
263 for the semantics. Availability: Unix.
264
265
266.. function:: setreuid(ruid, euid)
267
268 Set the current process's real and effective user ids. Availability: Unix.
269
270
271.. function:: setregid(rgid, egid)
272
273 Set the current process's real and effective group ids. Availability: Unix.
274
275
276.. function:: getsid(pid)
277
Christian Heimesfaf2f632008-01-06 16:59:19 +0000278 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000279 Availability: Unix.
280
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282.. function:: setsid()
283
Christian Heimesfaf2f632008-01-06 16:59:19 +0000284 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000285 Availability: Unix.
286
287
288.. function:: setuid(uid)
289
290 .. index:: single: user; id, setting
291
Christian Heimesfaf2f632008-01-06 16:59:19 +0000292 Set the current process's user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000293
Georg Brandl116aa622007-08-15 14:28:22 +0000294
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000295.. placed in this section since it relates to errno.... a little weak
Georg Brandl116aa622007-08-15 14:28:22 +0000296.. function:: strerror(code)
297
298 Return the error message corresponding to the error code in *code*.
299 Availability: Unix, Windows.
300
301
302.. function:: umask(mask)
303
Christian Heimesfaf2f632008-01-06 16:59:19 +0000304 Set the current numeric umask and return the previous umask. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000305 Unix, Windows.
306
307
308.. function:: uname()
309
310 .. index::
311 single: gethostname() (in module socket)
312 single: gethostbyaddr() (in module socket)
313
314 Return a 5-tuple containing information identifying the current operating
315 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
316 machine)``. Some systems truncate the nodename to 8 characters or to the
317 leading component; a better way to get the hostname is
318 :func:`socket.gethostname` or even
319 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
320 Unix.
321
322
323.. function:: unsetenv(varname)
324
325 .. index:: single: environment variables; deleting
326
327 Unset (delete) the environment variable named *varname*. Such changes to the
328 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
329 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
330
331 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
332 automatically translated into a corresponding call to :func:`unsetenv`; however,
333 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
334 preferable to delete items of ``os.environ``.
335
336
337.. _os-newstreams:
338
339File Object Creation
340--------------------
341
342These functions create new file objects. (See also :func:`open`.)
343
344
345.. function:: fdopen(fd[, mode[, bufsize]])
346
347 .. index:: single: I/O control; buffering
348
349 Return an open file object connected to the file descriptor *fd*. The *mode*
350 and *bufsize* arguments have the same meaning as the corresponding arguments to
351 the built-in :func:`open` function. Availability: Macintosh, Unix, Windows.
352
Georg Brandl55ac8f02007-09-01 13:51:09 +0000353 When specified, the *mode* argument must start with one of the letters
354 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Georg Brandl55ac8f02007-09-01 13:51:09 +0000356 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
357 set on the file descriptor (which the :cfunc:`fdopen` implementation already
358 does on most platforms).
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360
361.. function:: popen(command[, mode[, bufsize]])
362
363 Open a pipe to or from *command*. The return value is an open file object
364 connected to the pipe, which can be read or written depending on whether *mode*
365 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
366 the corresponding argument to the built-in :func:`open` function. The exit
367 status of the command (encoded in the format specified for :func:`wait`) is
368 available as the return value of the :meth:`close` method of the file object,
369 except that when the exit status is zero (termination without errors), ``None``
370 is returned. Availability: Macintosh, Unix, Windows.
371
372 .. deprecated:: 2.6
373 This function is obsolete. Use the :mod:`subprocess` module.
374
Georg Brandl116aa622007-08-15 14:28:22 +0000375
Georg Brandl116aa622007-08-15 14:28:22 +0000376.. _os-fd-ops:
377
378File Descriptor Operations
379--------------------------
380
381These functions operate on I/O streams referenced using file descriptors.
382
383File descriptors are small integers corresponding to a file that has been opened
384by the current process. For example, standard input is usually file descriptor
3850, standard output is 1, and standard error is 2. Further files opened by a
386process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
387is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
388by file descriptors.
389
390
391.. function:: close(fd)
392
393 Close file descriptor *fd*. Availability: Macintosh, Unix, Windows.
394
395 .. note::
396
397 This function is intended for low-level I/O and must be applied to a file
398 descriptor as returned by :func:`open` or :func:`pipe`. To close a "file
399 object" returned by the built-in function :func:`open` or by :func:`popen` or
400 :func:`fdopen`, use its :meth:`close` method.
401
402
Georg Brandl81f11302007-12-21 08:45:42 +0000403.. function:: device_encoding(fd)
404
405 Return a string describing the encoding of the device associated with *fd*
406 if it is connected to a terminal; else return :const:`None`.
407
408
Georg Brandl116aa622007-08-15 14:28:22 +0000409.. function:: dup(fd)
410
411 Return a duplicate of file descriptor *fd*. Availability: Macintosh, Unix,
412 Windows.
413
414
415.. function:: dup2(fd, fd2)
416
417 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
418 Availability: Macintosh, Unix, Windows.
419
420
Christian Heimes4e30a842007-11-30 22:12:06 +0000421.. function:: fchmod(fd, mode)
422
423 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
424 for :func:`chmod` for possible values of *mode*. Availability: Unix.
425
426
427.. function:: fchown(fd, uid, gid)
428
429 Change the owner and group id of the file given by *fd* to the numeric *uid*
430 and *gid*. To leave one of the ids unchanged, set it to -1.
431 Availability: Unix.
432
433
Georg Brandl116aa622007-08-15 14:28:22 +0000434.. function:: fdatasync(fd)
435
436 Force write of file with filedescriptor *fd* to disk. Does not force update of
437 metadata. Availability: Unix.
438
439
440.. function:: fpathconf(fd, name)
441
442 Return system configuration information relevant to an open file. *name*
443 specifies the configuration value to retrieve; it may be a string which is the
444 name of a defined system value; these names are specified in a number of
445 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
446 additional names as well. The names known to the host operating system are
447 given in the ``pathconf_names`` dictionary. For configuration variables not
448 included in that mapping, passing an integer for *name* is also accepted.
449 Availability: Macintosh, Unix.
450
451 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
452 specific value for *name* is not supported by the host system, even if it is
453 included in ``pathconf_names``, an :exc:`OSError` is raised with
454 :const:`errno.EINVAL` for the error number.
455
456
457.. function:: fstat(fd)
458
459 Return status for file descriptor *fd*, like :func:`stat`. Availability:
460 Macintosh, Unix, Windows.
461
462
463.. function:: fstatvfs(fd)
464
465 Return information about the filesystem containing the file associated with file
466 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
467
468
469.. function:: fsync(fd)
470
471 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
472 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
473
474 If you're starting with a Python file object *f*, first do ``f.flush()``, and
475 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
476 with *f* are written to disk. Availability: Macintosh, Unix, and Windows
477 starting in 2.2.3.
478
479
480.. function:: ftruncate(fd, length)
481
482 Truncate the file corresponding to file descriptor *fd*, so that it is at most
483 *length* bytes in size. Availability: Macintosh, Unix.
484
485
486.. function:: isatty(fd)
487
488 Return ``True`` if the file descriptor *fd* is open and connected to a
489 tty(-like) device, else ``False``. Availability: Macintosh, Unix.
490
491
492.. function:: lseek(fd, pos, how)
493
Christian Heimesfaf2f632008-01-06 16:59:19 +0000494 Set the current position of file descriptor *fd* to position *pos*, modified
495 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
496 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
497 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Georg Brandl116aa622007-08-15 14:28:22 +0000498 the file. Availability: Macintosh, Unix, Windows.
499
500
501.. function:: open(file, flags[, mode])
502
503 Open the file *file* and set various flags according to *flags* and possibly its
504 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
505 current umask value is first masked out. Return the file descriptor for the
506 newly opened file. Availability: Macintosh, Unix, Windows.
507
508 For a description of the flag and mode values, see the C run-time documentation;
509 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
510 this module too (see below).
511
512 .. note::
513
514 This function is intended for low-level I/O. For normal usage, use the built-in
515 function :func:`open`, which returns a "file object" with :meth:`read` and
516 :meth:`write` methods (and many more). To wrap a file descriptor in a "file
517 object", use :func:`fdopen`.
518
519
520.. function:: openpty()
521
522 .. index:: module: pty
523
524 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
525 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Christian Heimesfaf2f632008-01-06 16:59:19 +0000526 approach, use the :mod:`pty` module. Availability: Macintosh, some flavors of
Georg Brandl116aa622007-08-15 14:28:22 +0000527 Unix.
528
529
530.. function:: pipe()
531
532 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
533 and writing, respectively. Availability: Macintosh, Unix, Windows.
534
535
536.. function:: read(fd, n)
537
538 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
539 bytes read. If the end of the file referred to by *fd* has been reached, an
540 empty string is returned. Availability: Macintosh, Unix, Windows.
541
542 .. note::
543
544 This function is intended for low-level I/O and must be applied to a file
545 descriptor as returned by :func:`open` or :func:`pipe`. To read a "file object"
546 returned by the built-in function :func:`open` or by :func:`popen` or
Christian Heimesfaf2f632008-01-06 16:59:19 +0000547 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`read` or :meth:`readline`
Georg Brandl116aa622007-08-15 14:28:22 +0000548 methods.
549
550
551.. function:: tcgetpgrp(fd)
552
553 Return the process group associated with the terminal given by *fd* (an open
554 file descriptor as returned by :func:`open`). Availability: Macintosh, Unix.
555
556
557.. function:: tcsetpgrp(fd, pg)
558
559 Set the process group associated with the terminal given by *fd* (an open file
560 descriptor as returned by :func:`open`) to *pg*. Availability: Macintosh, Unix.
561
562
563.. function:: ttyname(fd)
564
565 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +0000566 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Georg Brandl116aa622007-08-15 14:28:22 +0000567 exception is raised. Availability:Macintosh, Unix.
568
569
570.. function:: write(fd, str)
571
572 Write the string *str* to file descriptor *fd*. Return the number of bytes
573 actually written. Availability: Macintosh, Unix, Windows.
574
575 .. note::
576
577 This function is intended for low-level I/O and must be applied to a file
578 descriptor as returned by :func:`open` or :func:`pipe`. To write a "file
579 object" returned by the built-in function :func:`open` or by :func:`popen` or
Christian Heimesfaf2f632008-01-06 16:59:19 +0000580 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`write`
Georg Brandl116aa622007-08-15 14:28:22 +0000581 method.
582
583The following data items are available for use in constructing the *flags*
584parameter to the :func:`open` function. Some items will not be available on all
585platforms. For descriptions of their availability and use, consult
586:manpage:`open(2)`.
587
588
589.. data:: O_RDONLY
590 O_WRONLY
591 O_RDWR
592 O_APPEND
593 O_CREAT
594 O_EXCL
595 O_TRUNC
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: Macintosh, Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000599
600
601.. data:: O_DSYNC
602 O_RSYNC
603 O_SYNC
604 O_NDELAY
605 O_NONBLOCK
606 O_NOCTTY
607 O_SHLOCK
608 O_EXLOCK
609
610 More options for the *flag* argument to the :func:`open` function. Availability:
611 Macintosh, Unix.
612
613
614.. data:: O_BINARY
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000615 O_NOINHERIT
Georg Brandl116aa622007-08-15 14:28:22 +0000616 O_SHORT_LIVED
617 O_TEMPORARY
618 O_RANDOM
619 O_SEQUENTIAL
620 O_TEXT
621
622 Options for the *flag* argument to the :func:`open` function. These can be
Christian Heimesfaf2f632008-01-06 16:59:19 +0000623 combined using the bitwise OR operator ``|``. Availability: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000624
625
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000626.. data:: O_DIRECT
627 O_DIRECTORY
628 O_NOFOLLOW
629 O_NOATIME
630
631 Options for the *flag* argument to the :func:`open` function. These are
632 GNU extensions and not present if they are not defined by the C library.
633
634
Georg Brandl116aa622007-08-15 14:28:22 +0000635.. data:: SEEK_SET
636 SEEK_CUR
637 SEEK_END
638
639 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
640 respectively. Availability: Windows, Macintosh, Unix.
641
Georg Brandl116aa622007-08-15 14:28:22 +0000642
643.. _os-file-dir:
644
645Files and Directories
646---------------------
647
648
649.. function:: access(path, mode)
650
651 Use the real uid/gid to test for access to *path*. Note that most operations
652 will use the effective uid/gid, therefore this routine can be used in a
653 suid/sgid environment to test if the invoking user has the specified access to
654 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
655 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
656 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
657 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
658 information. Availability: Macintosh, Unix, Windows.
659
660 .. note::
661
662 Using :func:`access` to check if a user is authorized to e.g. open a file before
663 actually doing so using :func:`open` creates a security hole, because the user
664 might exploit the short time interval between checking and opening the file to
665 manipulate it.
666
667 .. note::
668
669 I/O operations may fail even when :func:`access` indicates that they would
670 succeed, particularly for operations on network filesystems which may have
671 permissions semantics beyond the usual POSIX permission-bit model.
672
673
674.. data:: F_OK
675
676 Value to pass as the *mode* parameter of :func:`access` to test the existence of
677 *path*.
678
679
680.. data:: R_OK
681
682 Value to include in the *mode* parameter of :func:`access` to test the
683 readability of *path*.
684
685
686.. data:: W_OK
687
688 Value to include in the *mode* parameter of :func:`access` to test the
689 writability of *path*.
690
691
692.. data:: X_OK
693
694 Value to include in the *mode* parameter of :func:`access` to determine if
695 *path* can be executed.
696
697
698.. function:: chdir(path)
699
700 .. index:: single: directory; changing
701
702 Change the current working directory to *path*. Availability: Macintosh, Unix,
703 Windows.
704
705
706.. function:: fchdir(fd)
707
708 Change the current working directory to the directory represented by the file
709 descriptor *fd*. The descriptor must refer to an opened directory, not an open
710 file. Availability: Unix.
711
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713.. function:: getcwd()
714
715 Return a string representing the current working directory. Availability:
716 Macintosh, Unix, Windows.
717
718
719.. function:: getcwdu()
720
721 Return a Unicode object representing the current working directory.
722 Availability: Macintosh, Unix, Windows.
723
Georg Brandl116aa622007-08-15 14:28:22 +0000724
725.. function:: chflags(path, flags)
726
727 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
728 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
729
730 * ``UF_NODUMP``
731 * ``UF_IMMUTABLE``
732 * ``UF_APPEND``
733 * ``UF_OPAQUE``
734 * ``UF_NOUNLINK``
735 * ``SF_ARCHIVED``
736 * ``SF_IMMUTABLE``
737 * ``SF_APPEND``
738 * ``SF_NOUNLINK``
739 * ``SF_SNAPSHOT``
740
741 Availability: Macintosh, Unix.
742
Georg Brandl116aa622007-08-15 14:28:22 +0000743
744.. function:: chroot(path)
745
746 Change the root directory of the current process to *path*. Availability:
747 Macintosh, Unix.
748
Georg Brandl116aa622007-08-15 14:28:22 +0000749
750.. function:: chmod(path, mode)
751
752 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000753 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl116aa622007-08-15 14:28:22 +0000754 combinations of them:
755
756 * ``stat.S_ISUID``
757 * ``stat.S_ISGID``
758 * ``stat.S_ENFMT``
759 * ``stat.S_ISVTX``
760 * ``stat.S_IREAD``
761 * ``stat.S_IWRITE``
762 * ``stat.S_IEXEC``
763 * ``stat.S_IRWXU``
764 * ``stat.S_IRUSR``
765 * ``stat.S_IWUSR``
766 * ``stat.S_IXUSR``
767 * ``stat.S_IRWXG``
768 * ``stat.S_IRGRP``
769 * ``stat.S_IWGRP``
770 * ``stat.S_IXGRP``
771 * ``stat.S_IRWXO``
772 * ``stat.S_IROTH``
773 * ``stat.S_IWOTH``
774 * ``stat.S_IXOTH``
775
776 Availability: Macintosh, Unix, Windows.
777
778 .. note::
779
780 Although Windows supports :func:`chmod`, you can only set the file's read-only
781 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
782 constants or a corresponding integer value). All other bits are
783 ignored.
784
785
786.. function:: chown(path, uid, gid)
787
788 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
789 one of the ids unchanged, set it to -1. Availability: Macintosh, Unix.
790
791
792.. function:: lchflags(path, flags)
793
794 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
795 follow symbolic links. Availability: Unix.
796
Georg Brandl116aa622007-08-15 14:28:22 +0000797
Christian Heimes93852662007-12-01 12:22:32 +0000798.. function:: lchmod(path, mode)
799
800 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
801 affects the symlink rather than the target. See the docs for :func:`chmod`
802 for possible values of *mode*. Availability: Unix.
803
Christian Heimes93852662007-12-01 12:22:32 +0000804
Georg Brandl116aa622007-08-15 14:28:22 +0000805.. function:: lchown(path, uid, gid)
806
Christian Heimesfaf2f632008-01-06 16:59:19 +0000807 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Georg Brandl116aa622007-08-15 14:28:22 +0000808 function will not follow symbolic links. Availability: Macintosh, Unix.
809
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811.. function:: link(src, dst)
812
813 Create a hard link pointing to *src* named *dst*. Availability: Macintosh, Unix.
814
815
816.. function:: listdir(path)
817
818 Return a list containing the names of the entries in the directory. The list is
819 in arbitrary order. It does not include the special entries ``'.'`` and
820 ``'..'`` even if they are present in the directory. Availability: Macintosh,
821 Unix, Windows.
822
Georg Brandl55ac8f02007-09-01 13:51:09 +0000823 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
824 a list of Unicode objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826
827.. function:: lstat(path)
828
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000829 Like :func:`stat`, but do not follow symbolic links. This is an alias for
830 :func:`stat` on platforms that do not support symbolic links, such as
831 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000832
833
834.. function:: mkfifo(path[, mode])
835
836 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
837 *mode* is ``0666`` (octal). The current umask value is first masked out from
838 the mode. Availability: Macintosh, Unix.
839
840 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
841 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
842 rendezvous between "client" and "server" type processes: the server opens the
843 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
844 doesn't open the FIFO --- it just creates the rendezvous point.
845
846
847.. function:: mknod(filename[, mode=0600, device])
848
849 Create a filesystem node (file, device special file or named pipe) named
850 *filename*. *mode* specifies both the permissions to use and the type of node to
851 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
852 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
853 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
854 For ``stat.S_IFCHR`` and
855 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
856 :func:`os.makedev`), otherwise it is ignored.
857
Georg Brandl116aa622007-08-15 14:28:22 +0000858
859.. function:: major(device)
860
Christian Heimesfaf2f632008-01-06 16:59:19 +0000861 Extract the device major number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +0000862 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
863
Georg Brandl116aa622007-08-15 14:28:22 +0000864
865.. function:: minor(device)
866
Christian Heimesfaf2f632008-01-06 16:59:19 +0000867 Extract the device minor number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +0000868 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
869
Georg Brandl116aa622007-08-15 14:28:22 +0000870
871.. function:: makedev(major, minor)
872
Christian Heimesfaf2f632008-01-06 16:59:19 +0000873 Compose a raw device number from the major and minor device numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000874
Georg Brandl116aa622007-08-15 14:28:22 +0000875
876.. function:: mkdir(path[, mode])
877
878 Create a directory named *path* with numeric mode *mode*. The default *mode* is
879 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
880 current umask value is first masked out. Availability: Macintosh, Unix, Windows.
881
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000882 It is also possible to create temporary directories; see the
883 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
884
Georg Brandl116aa622007-08-15 14:28:22 +0000885
886.. function:: makedirs(path[, mode])
887
888 .. index::
889 single: directory; creating
890 single: UNC paths; and os.makedirs()
891
892 Recursive directory creation function. Like :func:`mkdir`, but makes all
893 intermediate-level directories needed to contain the leaf directory. Throws an
894 :exc:`error` exception if the leaf directory already exists or cannot be
895 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
896 ignored. Where it is used, the current umask value is first masked out.
897
898 .. note::
899
900 :func:`makedirs` will become confused if the path elements to create include
Christian Heimesfaf2f632008-01-06 16:59:19 +0000901 :data:`os.pardir`.
Georg Brandl116aa622007-08-15 14:28:22 +0000902
Georg Brandl55ac8f02007-09-01 13:51:09 +0000903 This function handles UNC paths correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000904
905
906.. function:: pathconf(path, name)
907
908 Return system configuration information relevant to a named file. *name*
909 specifies the configuration value to retrieve; it may be a string which is the
910 name of a defined system value; these names are specified in a number of
911 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
912 additional names as well. The names known to the host operating system are
913 given in the ``pathconf_names`` dictionary. For configuration variables not
914 included in that mapping, passing an integer for *name* is also accepted.
915 Availability: Macintosh, Unix.
916
917 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
918 specific value for *name* is not supported by the host system, even if it is
919 included in ``pathconf_names``, an :exc:`OSError` is raised with
920 :const:`errno.EINVAL` for the error number.
921
922
923.. data:: pathconf_names
924
925 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
926 the integer values defined for those names by the host operating system. This
927 can be used to determine the set of names known to the system. Availability:
928 Macintosh, Unix.
929
930
931.. function:: readlink(path)
932
933 Return a string representing the path to which the symbolic link points. The
934 result may be either an absolute or relative pathname; if it is relative, it may
935 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
936 result)``.
937
Georg Brandl55ac8f02007-09-01 13:51:09 +0000938 If the *path* is a Unicode object, the result will also be a Unicode object.
Georg Brandl116aa622007-08-15 14:28:22 +0000939
940 Availability: Macintosh, Unix.
941
942
943.. function:: remove(path)
944
945 Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
946 :func:`rmdir` below to remove a directory. This is identical to the
947 :func:`unlink` function documented below. On Windows, attempting to remove a
948 file that is in use causes an exception to be raised; on Unix, the directory
949 entry is removed but the storage allocated to the file is not made available
950 until the original file is no longer in use. Availability: Macintosh, Unix,
951 Windows.
952
953
954.. function:: removedirs(path)
955
956 .. index:: single: directory; deleting
957
Christian Heimesfaf2f632008-01-06 16:59:19 +0000958 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000959 leaf directory is successfully removed, :func:`removedirs` tries to
960 successively remove every parent directory mentioned in *path* until an error
961 is raised (which is ignored, because it generally means that a parent directory
962 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
963 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
964 they are empty. Raises :exc:`OSError` if the leaf directory could not be
965 successfully removed.
966
Georg Brandl116aa622007-08-15 14:28:22 +0000967
968.. function:: rename(src, dst)
969
970 Rename the file or directory *src* to *dst*. If *dst* is a directory,
971 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Christian Heimesfaf2f632008-01-06 16:59:19 +0000972 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl116aa622007-08-15 14:28:22 +0000973 Unix flavors if *src* and *dst* are on different filesystems. If successful,
974 the renaming will be an atomic operation (this is a POSIX requirement). On
975 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
976 file; there may be no way to implement an atomic rename when *dst* names an
977 existing file. Availability: Macintosh, Unix, Windows.
978
979
980.. function:: renames(old, new)
981
982 Recursive directory or file renaming function. Works like :func:`rename`, except
983 creation of any intermediate directories needed to make the new pathname good is
984 attempted first. After the rename, directories corresponding to rightmost path
985 segments of the old name will be pruned away using :func:`removedirs`.
986
Georg Brandl116aa622007-08-15 14:28:22 +0000987 .. note::
988
989 This function can fail with the new directory structure made if you lack
990 permissions needed to remove the leaf directory or file.
991
992
993.. function:: rmdir(path)
994
995 Remove the directory *path*. Availability: Macintosh, Unix, Windows.
996
997
998.. function:: stat(path)
999
1000 Perform a :cfunc:`stat` system call on the given path. The return value is an
1001 object whose attributes correspond to the members of the :ctype:`stat`
1002 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1003 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
Christian Heimesfaf2f632008-01-06 16:59:19 +00001004 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
Georg Brandl116aa622007-08-15 14:28:22 +00001005 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1006 access), :attr:`st_mtime` (time of most recent content modification),
1007 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1008 Unix, or the time of creation on Windows)::
1009
1010 >>> import os
1011 >>> statinfo = os.stat('somefile.txt')
1012 >>> statinfo
1013 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1014 >>> statinfo.st_size
1015 926L
1016 >>>
1017
Georg Brandl116aa622007-08-15 14:28:22 +00001018
1019 On some Unix systems (such as Linux), the following attributes may also be
1020 available: :attr:`st_blocks` (number of blocks allocated for file),
1021 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1022 inode device). :attr:`st_flags` (user defined flags for file).
1023
1024 On other Unix systems (such as FreeBSD), the following attributes may be
1025 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1026 (file generation number), :attr:`st_birthtime` (time of file creation).
1027
1028 On Mac OS systems, the following attributes may also be available:
1029 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1030
Georg Brandl116aa622007-08-15 14:28:22 +00001031 .. index:: module: stat
1032
1033 For backward compatibility, the return value of :func:`stat` is also accessible
1034 as a tuple of at least 10 integers giving the most important (and portable)
1035 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1036 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1037 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1038 :attr:`st_ctime`. More items may be added at the end by some implementations.
1039 The standard module :mod:`stat` defines functions and constants that are useful
1040 for extracting information from a :ctype:`stat` structure. (On Windows, some
1041 items are filled with dummy values.)
1042
1043 .. note::
1044
1045 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1046 :attr:`st_ctime` members depends on the operating system and the file system.
1047 For example, on Windows systems using the FAT or FAT32 file systems,
1048 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1049 resolution. See your operating system documentation for details.
1050
1051 Availability: Macintosh, Unix, Windows.
1052
Georg Brandl116aa622007-08-15 14:28:22 +00001053
1054.. function:: stat_float_times([newvalue])
1055
1056 Determine whether :class:`stat_result` represents time stamps as float objects.
1057 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1058 ``False``, future calls return ints. If *newvalue* is omitted, return the
1059 current setting.
1060
1061 For compatibility with older Python versions, accessing :class:`stat_result` as
1062 a tuple always returns integers.
1063
Georg Brandl55ac8f02007-09-01 13:51:09 +00001064 Python now returns float values by default. Applications which do not work
1065 correctly with floating point time stamps can use this function to restore the
1066 old behaviour.
Georg Brandl116aa622007-08-15 14:28:22 +00001067
1068 The resolution of the timestamps (that is the smallest possible fraction)
1069 depends on the system. Some systems only support second resolution; on these
1070 systems, the fraction will always be zero.
1071
1072 It is recommended that this setting is only changed at program startup time in
1073 the *__main__* module; libraries should never change this setting. If an
1074 application uses a library that works incorrectly if floating point time stamps
1075 are processed, this application should turn the feature off until the library
1076 has been corrected.
1077
1078
1079.. function:: statvfs(path)
1080
1081 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1082 an object whose attributes describe the filesystem on the given path, and
1083 correspond to the members of the :ctype:`statvfs` structure, namely:
1084 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1085 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1086 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1087
1088 .. index:: module: statvfs
1089
1090 For backward compatibility, the return value is also accessible as a tuple whose
1091 values correspond to the attributes, in the order given above. The standard
1092 module :mod:`statvfs` defines constants that are useful for extracting
1093 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1094 this remains useful when writing code that needs to work with versions of Python
1095 that don't support accessing the fields as attributes.
1096
Georg Brandl116aa622007-08-15 14:28:22 +00001097
1098.. function:: symlink(src, dst)
1099
1100 Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
1101
1102
Georg Brandl116aa622007-08-15 14:28:22 +00001103.. function:: unlink(path)
1104
1105 Remove the file *path*. This is the same function as :func:`remove`; the
1106 :func:`unlink` name is its traditional Unix name. Availability: Macintosh, Unix,
1107 Windows.
1108
1109
1110.. function:: utime(path, times)
1111
1112 Set the access and modified times of the file specified by *path*. If *times* is
1113 ``None``, then the file's access and modified times are set to the current time.
1114 Otherwise, *times* must be a 2-tuple of numbers, of the form ``(atime, mtime)``
1115 which is used to set the access and modified times, respectively. Whether a
1116 directory can be given for *path* depends on whether the operating system
1117 implements directories as files (for example, Windows does not). Note that the
1118 exact times you set here may not be returned by a subsequent :func:`stat` call,
1119 depending on the resolution with which your operating system records access and
1120 modification times; see :func:`stat`.
1121
Georg Brandl116aa622007-08-15 14:28:22 +00001122 Availability: Macintosh, Unix, Windows.
1123
1124
1125.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1126
1127 .. index::
1128 single: directory; walking
1129 single: directory; traversal
1130
Christian Heimesfaf2f632008-01-06 16:59:19 +00001131 Generate the file names in a directory tree by walking the tree
1132 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl116aa622007-08-15 14:28:22 +00001133 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1134 filenames)``.
1135
1136 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1137 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1138 *filenames* is a list of the names of the non-directory files in *dirpath*.
1139 Note that the names in the lists contain no path components. To get a full path
1140 (which begins with *top*) to a file or directory in *dirpath*, do
1141 ``os.path.join(dirpath, name)``.
1142
Christian Heimesfaf2f632008-01-06 16:59:19 +00001143 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001144 directory is generated before the triples for any of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001145 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001146 directory is generated after the triples for all of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001147 (directories are generated bottom-up).
Georg Brandl116aa622007-08-15 14:28:22 +00001148
Christian Heimesfaf2f632008-01-06 16:59:19 +00001149 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl116aa622007-08-15 14:28:22 +00001150 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1151 recurse into the subdirectories whose names remain in *dirnames*; this can be
1152 used to prune the search, impose a specific order of visiting, or even to inform
1153 :func:`walk` about directories the caller creates or renames before it resumes
Christian Heimesfaf2f632008-01-06 16:59:19 +00001154 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl116aa622007-08-15 14:28:22 +00001155 ineffective, because in bottom-up mode the directories in *dirnames* are
1156 generated before *dirpath* itself is generated.
1157
Christian Heimesfaf2f632008-01-06 16:59:19 +00001158 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl116aa622007-08-15 14:28:22 +00001159 argument *onerror* is specified, it should be a function; it will be called with
1160 one argument, an :exc:`OSError` instance. It can report the error to continue
1161 with the walk, or raise the exception to abort the walk. Note that the filename
1162 is available as the ``filename`` attribute of the exception object.
1163
1164 By default, :func:`walk` will not walk down into symbolic links that resolve to
Christian Heimesfaf2f632008-01-06 16:59:19 +00001165 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl116aa622007-08-15 14:28:22 +00001166 symlinks, on systems that support them.
1167
Georg Brandl116aa622007-08-15 14:28:22 +00001168 .. note::
1169
Christian Heimesfaf2f632008-01-06 16:59:19 +00001170 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl116aa622007-08-15 14:28:22 +00001171 link points to a parent directory of itself. :func:`walk` does not keep track of
1172 the directories it visited already.
1173
1174 .. note::
1175
1176 If you pass a relative pathname, don't change the current working directory
1177 between resumptions of :func:`walk`. :func:`walk` never changes the current
1178 directory, and assumes that its caller doesn't either.
1179
1180 This example displays the number of bytes taken by non-directory files in each
1181 directory under the starting directory, except that it doesn't look under any
1182 CVS subdirectory::
1183
1184 import os
1185 from os.path import join, getsize
1186 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001187 print(root, "consumes", end=" ")
1188 print(sum(getsize(join(root, name)) for name in files), end=" ")
1189 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00001190 if 'CVS' in dirs:
1191 dirs.remove('CVS') # don't visit CVS directories
1192
Christian Heimesfaf2f632008-01-06 16:59:19 +00001193 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl116aa622007-08-15 14:28:22 +00001194 doesn't allow deleting a directory before the directory is empty::
1195
Christian Heimesfaf2f632008-01-06 16:59:19 +00001196 # Delete everything reachable from the directory named in "top",
Georg Brandl116aa622007-08-15 14:28:22 +00001197 # assuming there are no symbolic links.
1198 # CAUTION: This is dangerous! For example, if top == '/', it
1199 # could delete all your disk files.
1200 import os
1201 for root, dirs, files in os.walk(top, topdown=False):
1202 for name in files:
1203 os.remove(os.path.join(root, name))
1204 for name in dirs:
1205 os.rmdir(os.path.join(root, name))
1206
Georg Brandl116aa622007-08-15 14:28:22 +00001207
1208.. _os-process:
1209
1210Process Management
1211------------------
1212
1213These functions may be used to create and manage processes.
1214
1215The various :func:`exec\*` functions take a list of arguments for the new
1216program loaded into the process. In each case, the first of these arguments is
1217passed to the new program as its own name rather than as an argument a user may
1218have typed on a command line. For the C programmer, this is the ``argv[0]``
1219passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1220['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1221to be ignored.
1222
1223
1224.. function:: abort()
1225
1226 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1227 behavior is to produce a core dump; on Windows, the process immediately returns
1228 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1229 to register a handler for :const:`SIGABRT` will behave differently.
1230 Availability: Macintosh, Unix, Windows.
1231
1232
1233.. function:: execl(path, arg0, arg1, ...)
1234 execle(path, arg0, arg1, ..., env)
1235 execlp(file, arg0, arg1, ...)
1236 execlpe(file, arg0, arg1, ..., env)
1237 execv(path, args)
1238 execve(path, args, env)
1239 execvp(file, args)
1240 execvpe(file, args, env)
1241
1242 These functions all execute a new program, replacing the current process; they
1243 do not return. On Unix, the new executable is loaded into the current process,
Christian Heimesfaf2f632008-01-06 16:59:19 +00001244 and will have the same process id as the caller. Errors will be reported as
Georg Brandl116aa622007-08-15 14:28:22 +00001245 :exc:`OSError` exceptions.
1246
Christian Heimesfaf2f632008-01-06 16:59:19 +00001247 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1248 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001249 to work with if the number of parameters is fixed when the code is written; the
1250 individual parameters simply become additional parameters to the :func:`execl\*`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001251 functions. The "v" variants are good when the number of parameters is
Georg Brandl116aa622007-08-15 14:28:22 +00001252 variable, with the arguments being passed in a list or tuple as the *args*
1253 parameter. In either case, the arguments to the child process should start with
1254 the name of the command being run, but this is not enforced.
1255
Christian Heimesfaf2f632008-01-06 16:59:19 +00001256 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001257 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1258 :envvar:`PATH` environment variable to locate the program *file*. When the
1259 environment is being replaced (using one of the :func:`exec\*e` variants,
1260 discussed in the next paragraph), the new environment is used as the source of
1261 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1262 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1263 locate the executable; *path* must contain an appropriate absolute or relative
1264 path.
1265
1266 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Christian Heimesfaf2f632008-01-06 16:59:19 +00001267 that these all end in "e"), the *env* parameter must be a mapping which is
Georg Brandl116aa622007-08-15 14:28:22 +00001268 used to define the environment variables for the new process; the :func:`execl`,
1269 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1270 inherit the environment of the current process. Availability: Macintosh, Unix,
1271 Windows.
1272
1273
1274.. function:: _exit(n)
1275
1276 Exit to the system with status *n*, without calling cleanup handlers, flushing
1277 stdio buffers, etc. Availability: Macintosh, Unix, Windows.
1278
1279 .. note::
1280
1281 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1282 be used in the child process after a :func:`fork`.
1283
Christian Heimesfaf2f632008-01-06 16:59:19 +00001284The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl116aa622007-08-15 14:28:22 +00001285although they are not required. These are typically used for system programs
1286written in Python, such as a mail server's external command delivery program.
1287
1288.. note::
1289
1290 Some of these may not be available on all Unix platforms, since there is some
1291 variation. These constants are defined where they are defined by the underlying
1292 platform.
1293
1294
1295.. data:: EX_OK
1296
1297 Exit code that means no error occurred. Availability: Macintosh, Unix.
1298
Georg Brandl116aa622007-08-15 14:28:22 +00001299
1300.. data:: EX_USAGE
1301
1302 Exit code that means the command was used incorrectly, such as when the wrong
1303 number of arguments are given. Availability: Macintosh, Unix.
1304
Georg Brandl116aa622007-08-15 14:28:22 +00001305
1306.. data:: EX_DATAERR
1307
1308 Exit code that means the input data was incorrect. Availability: Macintosh,
1309 Unix.
1310
Georg Brandl116aa622007-08-15 14:28:22 +00001311
1312.. data:: EX_NOINPUT
1313
1314 Exit code that means an input file did not exist or was not readable.
1315 Availability: Macintosh, Unix.
1316
Georg Brandl116aa622007-08-15 14:28:22 +00001317
1318.. data:: EX_NOUSER
1319
1320 Exit code that means a specified user did not exist. Availability: Macintosh,
1321 Unix.
1322
Georg Brandl116aa622007-08-15 14:28:22 +00001323
1324.. data:: EX_NOHOST
1325
1326 Exit code that means a specified host did not exist. Availability: Macintosh,
1327 Unix.
1328
Georg Brandl116aa622007-08-15 14:28:22 +00001329
1330.. data:: EX_UNAVAILABLE
1331
1332 Exit code that means that a required service is unavailable. Availability:
1333 Macintosh, Unix.
1334
Georg Brandl116aa622007-08-15 14:28:22 +00001335
1336.. data:: EX_SOFTWARE
1337
1338 Exit code that means an internal software error was detected. Availability:
1339 Macintosh, Unix.
1340
Georg Brandl116aa622007-08-15 14:28:22 +00001341
1342.. data:: EX_OSERR
1343
1344 Exit code that means an operating system error was detected, such as the
1345 inability to fork or create a pipe. Availability: Macintosh, Unix.
1346
Georg Brandl116aa622007-08-15 14:28:22 +00001347
1348.. data:: EX_OSFILE
1349
1350 Exit code that means some system file did not exist, could not be opened, or had
1351 some other kind of error. Availability: Macintosh, Unix.
1352
Georg Brandl116aa622007-08-15 14:28:22 +00001353
1354.. data:: EX_CANTCREAT
1355
1356 Exit code that means a user specified output file could not be created.
1357 Availability: Macintosh, Unix.
1358
Georg Brandl116aa622007-08-15 14:28:22 +00001359
1360.. data:: EX_IOERR
1361
1362 Exit code that means that an error occurred while doing I/O on some file.
1363 Availability: Macintosh, Unix.
1364
Georg Brandl116aa622007-08-15 14:28:22 +00001365
1366.. data:: EX_TEMPFAIL
1367
1368 Exit code that means a temporary failure occurred. This indicates something
1369 that may not really be an error, such as a network connection that couldn't be
1370 made during a retryable operation. Availability: Macintosh, Unix.
1371
Georg Brandl116aa622007-08-15 14:28:22 +00001372
1373.. data:: EX_PROTOCOL
1374
1375 Exit code that means that a protocol exchange was illegal, invalid, or not
1376 understood. Availability: Macintosh, Unix.
1377
Georg Brandl116aa622007-08-15 14:28:22 +00001378
1379.. data:: EX_NOPERM
1380
1381 Exit code that means that there were insufficient permissions to perform the
1382 operation (but not intended for file system problems). Availability: Macintosh,
1383 Unix.
1384
Georg Brandl116aa622007-08-15 14:28:22 +00001385
1386.. data:: EX_CONFIG
1387
1388 Exit code that means that some kind of configuration error occurred.
1389 Availability: Macintosh, Unix.
1390
Georg Brandl116aa622007-08-15 14:28:22 +00001391
1392.. data:: EX_NOTFOUND
1393
1394 Exit code that means something like "an entry was not found". Availability:
1395 Macintosh, Unix.
1396
Georg Brandl116aa622007-08-15 14:28:22 +00001397
1398.. function:: fork()
1399
Christian Heimesfaf2f632008-01-06 16:59:19 +00001400 Fork a child process. Return ``0`` in the child and the child's process id in the
Georg Brandl116aa622007-08-15 14:28:22 +00001401 parent. Availability: Macintosh, Unix.
1402
1403
1404.. function:: forkpty()
1405
1406 Fork a child process, using a new pseudo-terminal as the child's controlling
1407 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1408 new child's process id in the parent, and *fd* is the file descriptor of the
1409 master end of the pseudo-terminal. For a more portable approach, use the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001410 :mod:`pty` module. Availability: Macintosh, some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001411
1412
1413.. function:: kill(pid, sig)
1414
1415 .. index::
1416 single: process; killing
1417 single: process; signalling
1418
1419 Send signal *sig* to the process *pid*. Constants for the specific signals
1420 available on the host platform are defined in the :mod:`signal` module.
1421 Availability: Macintosh, Unix.
1422
1423
1424.. function:: killpg(pgid, sig)
1425
1426 .. index::
1427 single: process; killing
1428 single: process; signalling
1429
1430 Send the signal *sig* to the process group *pgid*. Availability: Macintosh,
1431 Unix.
1432
Georg Brandl116aa622007-08-15 14:28:22 +00001433
1434.. function:: nice(increment)
1435
1436 Add *increment* to the process's "niceness". Return the new niceness.
1437 Availability: Macintosh, Unix.
1438
1439
1440.. function:: plock(op)
1441
1442 Lock program segments into memory. The value of *op* (defined in
1443 ``<sys/lock.h>``) determines which segments are locked. Availability: Macintosh,
1444 Unix.
1445
1446
1447.. function:: popen(...)
1448 :noindex:
1449
1450 Run child processes, returning opened pipes for communications. These functions
1451 are described in section :ref:`os-newstreams`.
1452
1453
1454.. function:: spawnl(mode, path, ...)
1455 spawnle(mode, path, ..., env)
1456 spawnlp(mode, file, ...)
1457 spawnlpe(mode, file, ..., env)
1458 spawnv(mode, path, args)
1459 spawnve(mode, path, args, env)
1460 spawnvp(mode, file, args)
1461 spawnvpe(mode, file, args, env)
1462
1463 Execute the program *path* in a new process.
1464
1465 (Note that the :mod:`subprocess` module provides more powerful facilities for
1466 spawning new processes and retrieving their results; using that module is
1467 preferable to using these functions.)
1468
Christian Heimesfaf2f632008-01-06 16:59:19 +00001469 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl116aa622007-08-15 14:28:22 +00001470 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1471 exits normally, or ``-signal``, where *signal* is the signal that killed the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001472 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl116aa622007-08-15 14:28:22 +00001473 be used with the :func:`waitpid` function.
1474
Christian Heimesfaf2f632008-01-06 16:59:19 +00001475 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1476 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001477 to work with if the number of parameters is fixed when the code is written; the
1478 individual parameters simply become additional parameters to the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001479 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl116aa622007-08-15 14:28:22 +00001480 parameters is variable, with the arguments being passed in a list or tuple as
1481 the *args* parameter. In either case, the arguments to the child process must
1482 start with the name of the command being run.
1483
Christian Heimesfaf2f632008-01-06 16:59:19 +00001484 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001485 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1486 :envvar:`PATH` environment variable to locate the program *file*. When the
1487 environment is being replaced (using one of the :func:`spawn\*e` variants,
1488 discussed in the next paragraph), the new environment is used as the source of
1489 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1490 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1491 :envvar:`PATH` variable to locate the executable; *path* must contain an
1492 appropriate absolute or relative path.
1493
1494 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001495 (note that these all end in "e"), the *env* parameter must be a mapping
Georg Brandl116aa622007-08-15 14:28:22 +00001496 which is used to define the environment variables for the new process; the
1497 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1498 the new process to inherit the environment of the current process.
1499
1500 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1501 equivalent::
1502
1503 import os
1504 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1505
1506 L = ['cp', 'index.html', '/dev/null']
1507 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1508
1509 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1510 and :func:`spawnvpe` are not available on Windows.
1511
Georg Brandl116aa622007-08-15 14:28:22 +00001512
1513.. data:: P_NOWAIT
1514 P_NOWAITO
1515
1516 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1517 functions. If either of these values is given, the :func:`spawn\*` functions
Christian Heimesfaf2f632008-01-06 16:59:19 +00001518 will return as soon as the new process has been created, with the process id as
Georg Brandl116aa622007-08-15 14:28:22 +00001519 the return value. Availability: Macintosh, Unix, Windows.
1520
Georg Brandl116aa622007-08-15 14:28:22 +00001521
1522.. data:: P_WAIT
1523
1524 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1525 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1526 return until the new process has run to completion and will return the exit code
1527 of the process the run is successful, or ``-signal`` if a signal kills the
1528 process. Availability: Macintosh, Unix, Windows.
1529
Georg Brandl116aa622007-08-15 14:28:22 +00001530
1531.. data:: P_DETACH
1532 P_OVERLAY
1533
1534 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1535 functions. These are less portable than those listed above. :const:`P_DETACH`
1536 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1537 console of the calling process. If :const:`P_OVERLAY` is used, the current
1538 process will be replaced; the :func:`spawn\*` function will not return.
1539 Availability: Windows.
1540
Georg Brandl116aa622007-08-15 14:28:22 +00001541
1542.. function:: startfile(path[, operation])
1543
1544 Start a file with its associated application.
1545
1546 When *operation* is not specified or ``'open'``, this acts like double-clicking
1547 the file in Windows Explorer, or giving the file name as an argument to the
1548 :program:`start` command from the interactive command shell: the file is opened
1549 with whatever application (if any) its extension is associated.
1550
1551 When another *operation* is given, it must be a "command verb" that specifies
1552 what should be done with the file. Common verbs documented by Microsoft are
1553 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1554 ``'find'`` (to be used on directories).
1555
1556 :func:`startfile` returns as soon as the associated application is launched.
1557 There is no option to wait for the application to close, and no way to retrieve
1558 the application's exit status. The *path* parameter is relative to the current
1559 directory. If you want to use an absolute path, make sure the first character
1560 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1561 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1562 the path is properly encoded for Win32. Availability: Windows.
1563
Georg Brandl116aa622007-08-15 14:28:22 +00001564
1565.. function:: system(command)
1566
1567 Execute the command (a string) in a subshell. This is implemented by calling
1568 the Standard C function :cfunc:`system`, and has the same limitations. Changes
Christian Heimesfaf2f632008-01-06 16:59:19 +00001569 to :data:`os.environ`, :data:`sys.stdin`, etc. are not reflected in the
1570 environment of the executed command.
Georg Brandl116aa622007-08-15 14:28:22 +00001571
1572 On Unix, the return value is the exit status of the process encoded in the
1573 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1574 of the return value of the C :cfunc:`system` function, so the return value of
1575 the Python function is system-dependent.
1576
1577 On Windows, the return value is that returned by the system shell after running
1578 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1579 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1580 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1581 the command run; on systems using a non-native shell, consult your shell
1582 documentation.
1583
1584 Availability: Macintosh, Unix, Windows.
1585
1586 The :mod:`subprocess` module provides more powerful facilities for spawning new
1587 processes and retrieving their results; using that module is preferable to using
1588 this function.
1589
1590
1591.. function:: times()
1592
1593 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1594 other) times, in seconds. The items are: user time, system time, children's
1595 user time, children's system time, and elapsed real time since a fixed point in
1596 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
1597 corresponding Windows Platform API documentation. Availability: Macintosh, Unix,
1598 Windows.
1599
1600
1601.. function:: wait()
1602
1603 Wait for completion of a child process, and return a tuple containing its pid
1604 and exit status indication: a 16-bit number, whose low byte is the signal number
1605 that killed the process, and whose high byte is the exit status (if the signal
1606 number is zero); the high bit of the low byte is set if a core file was
1607 produced. Availability: Macintosh, Unix.
1608
1609
1610.. function:: waitpid(pid, options)
1611
1612 The details of this function differ on Unix and Windows.
1613
1614 On Unix: Wait for completion of a child process given by process id *pid*, and
1615 return a tuple containing its process id and exit status indication (encoded as
1616 for :func:`wait`). The semantics of the call are affected by the value of the
1617 integer *options*, which should be ``0`` for normal operation.
1618
1619 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1620 that specific process. If *pid* is ``0``, the request is for the status of any
1621 child in the process group of the current process. If *pid* is ``-1``, the
1622 request pertains to any child of the current process. If *pid* is less than
1623 ``-1``, status is requested for any process in the process group ``-pid`` (the
1624 absolute value of *pid*).
1625
1626 On Windows: Wait for completion of a process given by process handle *pid*, and
1627 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1628 (shifting makes cross-platform use of the function easier). A *pid* less than or
1629 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1630 value of integer *options* has no effect. *pid* can refer to any process whose
1631 id is known, not necessarily a child process. The :func:`spawn` functions called
1632 with :const:`P_NOWAIT` return suitable process handles.
1633
1634
1635.. function:: wait3([options])
1636
1637 Similar to :func:`waitpid`, except no process id argument is given and a
1638 3-element tuple containing the child's process id, exit status indication, and
1639 resource usage information is returned. Refer to :mod:`resource`.\
1640 :func:`getrusage` for details on resource usage information. The option
1641 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1642 Availability: Unix.
1643
Georg Brandl116aa622007-08-15 14:28:22 +00001644
1645.. function:: wait4(pid, options)
1646
1647 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1648 process id, exit status indication, and resource usage information is returned.
1649 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1650 information. The arguments to :func:`wait4` are the same as those provided to
1651 :func:`waitpid`. Availability: Unix.
1652
Georg Brandl116aa622007-08-15 14:28:22 +00001653
1654.. data:: WNOHANG
1655
1656 The option for :func:`waitpid` to return immediately if no child process status
1657 is available immediately. The function returns ``(0, 0)`` in this case.
1658 Availability: Macintosh, Unix.
1659
1660
1661.. data:: WCONTINUED
1662
1663 This option causes child processes to be reported if they have been continued
1664 from a job control stop since their status was last reported. Availability: Some
1665 Unix systems.
1666
Georg Brandl116aa622007-08-15 14:28:22 +00001667
1668.. data:: WUNTRACED
1669
1670 This option causes child processes to be reported if they have been stopped but
1671 their current state has not been reported since they were stopped. Availability:
1672 Macintosh, Unix.
1673
Georg Brandl116aa622007-08-15 14:28:22 +00001674
1675The following functions take a process status code as returned by
1676:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1677used to determine the disposition of a process.
1678
Georg Brandl116aa622007-08-15 14:28:22 +00001679.. function:: WCOREDUMP(status)
1680
Christian Heimesfaf2f632008-01-06 16:59:19 +00001681 Return ``True`` if a core dump was generated for the process, otherwise
1682 return ``False``. Availability: Macintosh, Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001683
Georg Brandl116aa622007-08-15 14:28:22 +00001684
1685.. function:: WIFCONTINUED(status)
1686
Christian Heimesfaf2f632008-01-06 16:59:19 +00001687 Return ``True`` if the process has been continued from a job control stop,
1688 otherwise return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001689
Georg Brandl116aa622007-08-15 14:28:22 +00001690
1691.. function:: WIFSTOPPED(status)
1692
Christian Heimesfaf2f632008-01-06 16:59:19 +00001693 Return ``True`` if the process has been stopped, otherwise return
Georg Brandl116aa622007-08-15 14:28:22 +00001694 ``False``. Availability: Unix.
1695
1696
1697.. function:: WIFSIGNALED(status)
1698
Christian Heimesfaf2f632008-01-06 16:59:19 +00001699 Return ``True`` if the process exited due to a signal, otherwise return
Georg Brandl116aa622007-08-15 14:28:22 +00001700 ``False``. Availability: Macintosh, Unix.
1701
1702
1703.. function:: WIFEXITED(status)
1704
Christian Heimesfaf2f632008-01-06 16:59:19 +00001705 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
1706 otherwise return ``False``. Availability: Macintosh, Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001707
1708
1709.. function:: WEXITSTATUS(status)
1710
1711 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1712 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
1713 Availability: Macintosh, Unix.
1714
1715
1716.. function:: WSTOPSIG(status)
1717
1718 Return the signal which caused the process to stop. Availability: Macintosh,
1719 Unix.
1720
1721
1722.. function:: WTERMSIG(status)
1723
1724 Return the signal which caused the process to exit. Availability: Macintosh,
1725 Unix.
1726
1727
1728.. _os-path:
1729
1730Miscellaneous System Information
1731--------------------------------
1732
1733
1734.. function:: confstr(name)
1735
1736 Return string-valued system configuration values. *name* specifies the
1737 configuration value to retrieve; it may be a string which is the name of a
1738 defined system value; these names are specified in a number of standards (POSIX,
1739 Unix 95, Unix 98, and others). Some platforms define additional names as well.
1740 The names known to the host operating system are given as the keys of the
1741 ``confstr_names`` dictionary. For configuration variables not included in that
1742 mapping, passing an integer for *name* is also accepted. Availability:
1743 Macintosh, Unix.
1744
1745 If the configuration value specified by *name* isn't defined, ``None`` is
1746 returned.
1747
1748 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1749 specific value for *name* is not supported by the host system, even if it is
1750 included in ``confstr_names``, an :exc:`OSError` is raised with
1751 :const:`errno.EINVAL` for the error number.
1752
1753
1754.. data:: confstr_names
1755
1756 Dictionary mapping names accepted by :func:`confstr` 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
1760
1761.. function:: getloadavg()
1762
1763 Return the number of processes in the system run queue averaged over the last 1,
1764 5, and 15 minutes or raises :exc:`OSError` if the load average was
1765 unobtainable.
1766
Georg Brandl116aa622007-08-15 14:28:22 +00001767
1768.. function:: sysconf(name)
1769
1770 Return integer-valued system configuration values. If the configuration value
1771 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
1772 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
1773 provides information on the known names is given by ``sysconf_names``.
1774 Availability: Macintosh, Unix.
1775
1776
1777.. data:: sysconf_names
1778
1779 Dictionary mapping names accepted by :func:`sysconf` to the integer values
1780 defined for those names by the host operating system. This can be used to
1781 determine the set of names known to the system. Availability: Macintosh, Unix.
1782
Christian Heimesfaf2f632008-01-06 16:59:19 +00001783The following data values are used to support path manipulation operations. These
Georg Brandl116aa622007-08-15 14:28:22 +00001784are defined for all platforms.
1785
1786Higher-level operations on pathnames are defined in the :mod:`os.path` module.
1787
1788
1789.. data:: curdir
1790
1791 The constant string used by the operating system to refer to the current
1792 directory. For example: ``'.'`` for POSIX or ``':'`` for Mac OS 9. Also
1793 available via :mod:`os.path`.
1794
1795
1796.. data:: pardir
1797
1798 The constant string used by the operating system to refer to the parent
1799 directory. For example: ``'..'`` for POSIX or ``'::'`` for Mac OS 9. Also
1800 available via :mod:`os.path`.
1801
1802
1803.. data:: sep
1804
1805 The character used by the operating system to separate pathname components, for
1806 example, ``'/'`` for POSIX or ``':'`` for Mac OS 9. Note that knowing this is
1807 not sufficient to be able to parse or concatenate pathnames --- use
1808 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
1809 useful. Also available via :mod:`os.path`.
1810
1811
1812.. data:: altsep
1813
1814 An alternative character used by the operating system to separate pathname
1815 components, or ``None`` if only one separator character exists. This is set to
1816 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
1817 :mod:`os.path`.
1818
1819
1820.. data:: extsep
1821
1822 The character which separates the base filename from the extension; for example,
1823 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
1824
Georg Brandl116aa622007-08-15 14:28:22 +00001825
1826.. data:: pathsep
1827
1828 The character conventionally used by the operating system to separate search
1829 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
1830 Windows. Also available via :mod:`os.path`.
1831
1832
1833.. data:: defpath
1834
1835 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
1836 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
1837
1838
1839.. data:: linesep
1840
1841 The string used to separate (or, rather, terminate) lines on the current
1842 platform. This may be a single character, such as ``'\n'`` for POSIX or
1843 ``'\r'`` for Mac OS, or multiple characters, for example, ``'\r\n'`` for
1844 Windows. Do not use *os.linesep* as a line terminator when writing files opened
1845 in text mode (the default); use a single ``'\n'`` instead, on all platforms.
1846
1847
1848.. data:: devnull
1849
1850 The file path of the null device. For example: ``'/dev/null'`` for POSIX or
1851 ``'Dev:Nul'`` for Mac OS 9. Also available via :mod:`os.path`.
1852
Georg Brandl116aa622007-08-15 14:28:22 +00001853
1854.. _os-miscfunc:
1855
1856Miscellaneous Functions
1857-----------------------
1858
1859
1860.. function:: urandom(n)
1861
1862 Return a string of *n* random bytes suitable for cryptographic use.
1863
1864 This function returns random bytes from an OS-specific randomness source. The
1865 returned data should be unpredictable enough for cryptographic applications,
1866 though its exact quality depends on the OS implementation. On a UNIX-like
1867 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
1868 If a randomness source is not found, :exc:`NotImplementedError` will be raised.