blob: 805f2a24937f36439a7068000d6ffe2b4a913f7f [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
10functionality than importing a operating system dependent built-in module like
Mark Summerfieldddca9f02007-09-13 14:54: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
Mark Summerfieldac3d4292007-11-02 08:24:59 +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 Brandl8ec7f652007-08-15 14:28:01 +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
20there. The design of all Python's built-in operating system dependent modules
21is 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
38.. % Frank Stajano <fstajano@uk.research.att.com> complained that it
39.. % wasn't clear that the entries described in the subsections were all
40.. % available at the module level (most uses of subsections are
41.. % different); I think this is only a problem for the HTML version,
42.. % where the relationship may not be as clear.
43.. %
44
45
46.. exception:: error
47
48 .. index:: module: errno
49
50 This exception is raised when a function returns a system-related error (not for
51 illegal argument types or other incidental errors). This is also known as the
52 built-in exception :exc:`OSError`. The accompanying value is a pair containing
53 the numeric error code from :cdata:`errno` and the corresponding string, as
54 would be printed by the C function :cfunc:`perror`. See the module
55 :mod:`errno`, which contains names for the error codes defined by the underlying
56 operating system.
57
58 When exceptions are classes, this exception carries two attributes,
59 :attr:`errno` and :attr:`strerror`. The first holds the value of the C
60 :cdata:`errno` variable, and the latter holds the corresponding error message
61 from :cfunc:`strerror`. For exceptions that involve a file system path (such as
62 :func:`chdir` or :func:`unlink`), the exception instance will contain a third
63 attribute, :attr:`filename`, which is the file name passed to the function.
64
65
66.. data:: name
67
68 The name of the operating system dependent module imported. The following names
69 have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``,
70 ``'ce'``, ``'java'``, ``'riscos'``.
71
72
73.. data:: path
74
75 The corresponding operating system dependent standard module for pathname
76 operations, such as :mod:`posixpath` or :mod:`macpath`. Thus, given the proper
77 imports, ``os.path.split(file)`` is equivalent to but more portable than
78 ``posixpath.split(file)``. Note that this is also an importable module: it may
79 be imported directly as :mod:`os.path`.
80
81
82.. _os-procinfo:
83
84Process Parameters
85------------------
86
87These functions and data items provide information and operate on the current
88process and user.
89
90
91.. data:: environ
92
93 A mapping object representing the string environment. For example,
94 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
95 and is equivalent to ``getenv("HOME")`` in C.
96
97 This mapping is captured the first time the :mod:`os` module is imported,
98 typically during Python startup as part of processing :file:`site.py`. Changes
99 to the environment made after this time are not reflected in ``os.environ``,
100 except for changes made by modifying ``os.environ`` directly.
101
102 If the platform supports the :func:`putenv` function, this mapping may be used
103 to modify the environment as well as query the environment. :func:`putenv` will
104 be called automatically when the mapping is modified.
105
106 .. note::
107
108 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
109 to modify ``os.environ``.
110
111 .. note::
112
113 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause
114 memory leaks. Refer to the system documentation for :cfunc:`putenv`.
115
116 If :func:`putenv` is not provided, a modified copy of this mapping may be
117 passed to the appropriate process-creation functions to cause child processes
118 to use a modified environment.
119
Georg Brandl4a212682007-09-20 17:57:59 +0000120 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000121 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl4a212682007-09-20 17:57:59 +0000122 automatically when an item is deleted from ``os.environ``, and when
Georg Brandl1a94ec22007-10-24 21:40:38 +0000123 one of the :meth:`pop` or :meth:`clear` methods is called.
Georg Brandl4a212682007-09-20 17:57:59 +0000124
125 .. versionchanged:: 2.6
Georg Brandl1a94ec22007-10-24 21:40:38 +0000126 Also unset environment variables when calling :meth:`os.environ.clear`
127 and :meth:`os.environ.pop`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000128
129
130.. function:: chdir(path)
131 fchdir(fd)
132 getcwd()
133 :noindex:
134
135 These functions are described in :ref:`os-file-dir`.
136
137
138.. function:: ctermid()
139
140 Return the filename corresponding to the controlling terminal of the process.
141 Availability: Unix.
142
143
144.. function:: getegid()
145
146 Return the effective group id of the current process. This corresponds to the
147 'set id' bit on the file being executed in the current process. Availability:
148 Unix.
149
150
151.. function:: geteuid()
152
153 .. index:: single: user; effective id
154
155 Return the current process' effective user id. Availability: Unix.
156
157
158.. function:: getgid()
159
160 .. index:: single: process; group
161
162 Return the real group id of the current process. Availability: Unix.
163
164
165.. function:: getgroups()
166
167 Return list of supplemental group ids associated with the current process.
168 Availability: Unix.
169
170
171.. function:: getlogin()
172
173 Return the name of the user logged in on the controlling terminal of the
174 process. For most purposes, it is more useful to use the environment variable
175 :envvar:`LOGNAME` to find out who the user is, or
176 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
177 effective user ID. Availability: Unix.
178
179
180.. function:: getpgid(pid)
181
182 Return the process group id of the process with process id *pid*. If *pid* is 0,
183 the process group id of the current process is returned. Availability: Unix.
184
185 .. versionadded:: 2.3
186
187
188.. function:: getpgrp()
189
190 .. index:: single: process; group
191
192 Return the id of the current process group. Availability: Unix.
193
194
195.. function:: getpid()
196
197 .. index:: single: process; id
198
199 Return the current process id. Availability: Unix, Windows.
200
201
202.. function:: getppid()
203
204 .. index:: single: process; id of parent
205
206 Return the parent's process id. Availability: Unix.
207
208
209.. function:: getuid()
210
211 .. index:: single: user; id
212
213 Return the current process' user id. Availability: Unix.
214
215
216.. function:: getenv(varname[, value])
217
218 Return the value of the environment variable *varname* if it exists, or *value*
219 if it doesn't. *value* defaults to ``None``. Availability: most flavors of
220 Unix, Windows.
221
222
223.. function:: putenv(varname, value)
224
225 .. index:: single: environment variables; setting
226
227 Set the environment variable named *varname* to the string *value*. Such
228 changes to the environment affect subprocesses started with :func:`os.system`,
229 :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
230 Unix, Windows.
231
232 .. note::
233
234 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause
235 memory leaks. Refer to the system documentation for putenv.
236
237 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
238 automatically translated into corresponding calls to :func:`putenv`; however,
239 calls to :func:`putenv` don't update ``os.environ``, so it is actually
240 preferable to assign to items of ``os.environ``.
241
242
243.. function:: setegid(egid)
244
245 Set the current process's effective group id. Availability: Unix.
246
247
248.. function:: seteuid(euid)
249
250 Set the current process's effective user id. Availability: Unix.
251
252
253.. function:: setgid(gid)
254
255 Set the current process' group id. Availability: Unix.
256
257
258.. function:: setgroups(groups)
259
260 Set the list of supplemental group ids associated with the current process to
261 *groups*. *groups* must be a sequence, and each element must be an integer
262 identifying a group. This operation is typical available only to the superuser.
263 Availability: Unix.
264
265 .. versionadded:: 2.2
266
267
268.. function:: setpgrp()
269
270 Calls the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
271 which version is implemented (if any). See the Unix manual for the semantics.
272 Availability: Unix.
273
274
275.. function:: setpgid(pid, pgrp)
276
277 Calls the system call :cfunc:`setpgid` to set the process group id of the
278 process with id *pid* to the process group with id *pgrp*. See the Unix manual
279 for the semantics. Availability: Unix.
280
281
282.. function:: setreuid(ruid, euid)
283
284 Set the current process's real and effective user ids. Availability: Unix.
285
286
287.. function:: setregid(rgid, egid)
288
289 Set the current process's real and effective group ids. Availability: Unix.
290
291
292.. function:: getsid(pid)
293
294 Calls the system call :cfunc:`getsid`. See the Unix manual for the semantics.
295 Availability: Unix.
296
297 .. versionadded:: 2.4
298
299
300.. function:: setsid()
301
302 Calls the system call :cfunc:`setsid`. See the Unix manual for the semantics.
303 Availability: Unix.
304
305
306.. function:: setuid(uid)
307
308 .. index:: single: user; id, setting
309
310 Set the current process' user id. Availability: Unix.
311
312.. % placed in this section since it relates to errno.... a little weak
313
314
315.. function:: strerror(code)
316
317 Return the error message corresponding to the error code in *code*.
318 Availability: Unix, Windows.
319
320
321.. function:: umask(mask)
322
323 Set the current numeric umask and returns the previous umask. Availability:
324 Unix, Windows.
325
326
327.. function:: uname()
328
329 .. index::
330 single: gethostname() (in module socket)
331 single: gethostbyaddr() (in module socket)
332
333 Return a 5-tuple containing information identifying the current operating
334 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
335 machine)``. Some systems truncate the nodename to 8 characters or to the
336 leading component; a better way to get the hostname is
337 :func:`socket.gethostname` or even
338 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
339 Unix.
340
341
342.. function:: unsetenv(varname)
343
344 .. index:: single: environment variables; deleting
345
346 Unset (delete) the environment variable named *varname*. Such changes to the
347 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
348 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
349
350 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
351 automatically translated into a corresponding call to :func:`unsetenv`; however,
352 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
353 preferable to delete items of ``os.environ``.
354
355
356.. _os-newstreams:
357
358File Object Creation
359--------------------
360
361These functions create new file objects. (See also :func:`open`.)
362
363
364.. function:: fdopen(fd[, mode[, bufsize]])
365
366 .. index:: single: I/O control; buffering
367
368 Return an open file object connected to the file descriptor *fd*. The *mode*
369 and *bufsize* arguments have the same meaning as the corresponding arguments to
370 the built-in :func:`open` function. Availability: Macintosh, Unix, Windows.
371
372 .. versionchanged:: 2.3
373 When specified, the *mode* argument must now start with one of the letters
374 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
375
376 .. versionchanged:: 2.5
377 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
378 set on the file descriptor (which the :cfunc:`fdopen` implementation already
379 does on most platforms).
380
381
382.. function:: popen(command[, mode[, bufsize]])
383
384 Open a pipe to or from *command*. The return value is an open file object
385 connected to the pipe, which can be read or written depending on whether *mode*
386 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
387 the corresponding argument to the built-in :func:`open` function. The exit
388 status of the command (encoded in the format specified for :func:`wait`) is
389 available as the return value of the :meth:`close` method of the file object,
390 except that when the exit status is zero (termination without errors), ``None``
391 is returned. Availability: Macintosh, Unix, Windows.
392
393 .. deprecated:: 2.6
394 This function is obsolete. Use the :mod:`subprocess` module.
395
396 .. versionchanged:: 2.0
397 This function worked unreliably under Windows in earlier versions of Python.
398 This was due to the use of the :cfunc:`_popen` function from the libraries
399 provided with Windows. Newer versions of Python do not use the broken
400 implementation from the Windows libraries.
401
402
403.. function:: tmpfile()
404
405 Return a new file object opened in update mode (``w+b``). The file has no
406 directory entries associated with it and will be automatically deleted once
407 there are no file descriptors for the file. Availability: Macintosh, Unix,
408 Windows.
409
410There are a number of different :func:`popen\*` functions that provide slightly
411different ways to create subprocesses.
412
413.. deprecated:: 2.6
414 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
415 module.
416
417For each of the :func:`popen\*` variants, if *bufsize* is specified, it
418specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
419string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
420file objects should be opened in binary or text mode. The default value for
421*mode* is ``'t'``.
422
423Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
424case arguments will be passed directly to the program without shell intervention
425(as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
426(as with :func:`os.system`).
427
428These methods do not make it possible to retrieve the exit status from the child
429processes. The only way to control the input and output streams and also
430retrieve the return codes is to use the :mod:`subprocess` module; these are only
431available on Unix.
432
433For a discussion of possible deadlock conditions related to the use of these
434functions, see :ref:`popen2-flow-control`.
435
436
437.. function:: popen2(cmd[, mode[, bufsize]])
438
439 Executes *cmd* as a sub-process. Returns the file objects ``(child_stdin,
440 child_stdout)``.
441
442 .. deprecated:: 2.6
443 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
444 module.
445
446 Availability: Macintosh, Unix, Windows.
447
448 .. versionadded:: 2.0
449
450
451.. function:: popen3(cmd[, mode[, bufsize]])
452
453 Executes *cmd* as a sub-process. Returns the file objects ``(child_stdin,
454 child_stdout, child_stderr)``.
455
456 .. deprecated:: 2.6
457 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
458 module.
459
460 Availability: Macintosh, Unix, Windows.
461
462 .. versionadded:: 2.0
463
464
465.. function:: popen4(cmd[, mode[, bufsize]])
466
467 Executes *cmd* as a sub-process. Returns the file objects ``(child_stdin,
468 child_stdout_and_stderr)``.
469
470 .. deprecated:: 2.6
471 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
472 module.
473
474 Availability: Macintosh, Unix, Windows.
475
476 .. versionadded:: 2.0
477
478(Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
479point of view of the child process, so *child_stdin* is the child's standard
480input.)
481
482This functionality is also available in the :mod:`popen2` module using functions
483of the same names, but the return values of those functions have a different
484order.
485
486
487.. _os-fd-ops:
488
489File Descriptor Operations
490--------------------------
491
492These functions operate on I/O streams referenced using file descriptors.
493
494File descriptors are small integers corresponding to a file that has been opened
495by the current process. For example, standard input is usually file descriptor
4960, standard output is 1, and standard error is 2. Further files opened by a
497process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
498is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
499by file descriptors.
500
501
502.. function:: close(fd)
503
504 Close file descriptor *fd*. Availability: Macintosh, Unix, Windows.
505
506 .. note::
507
508 This function is intended for low-level I/O and must be applied to a file
509 descriptor as returned by :func:`open` or :func:`pipe`. To close a "file
510 object" returned by the built-in function :func:`open` or by :func:`popen` or
511 :func:`fdopen`, use its :meth:`close` method.
512
513
514.. function:: dup(fd)
515
516 Return a duplicate of file descriptor *fd*. Availability: Macintosh, Unix,
517 Windows.
518
519
520.. function:: dup2(fd, fd2)
521
522 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
523 Availability: Macintosh, Unix, Windows.
524
525
Christian Heimes36281872007-11-30 21:11:28 +0000526.. function:: fchmod(fd, mode)
527
528 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
529 for :func:`chmod` for possible values of *mode*. Availability: Unix.
530
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000531 .. versionadded:: 2.6
532
Christian Heimes36281872007-11-30 21:11:28 +0000533
534.. function:: fchown(fd, uid, gid)
535
536 Change the owner and group id of the file given by *fd* to the numeric *uid*
537 and *gid*. To leave one of the ids unchanged, set it to -1.
538 Availability: Unix.
539
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000540 .. versionadded:: 2.6
541
Christian Heimes36281872007-11-30 21:11:28 +0000542
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543.. function:: fdatasync(fd)
544
545 Force write of file with filedescriptor *fd* to disk. Does not force update of
546 metadata. Availability: Unix.
547
548
549.. function:: fpathconf(fd, name)
550
551 Return system configuration information relevant to an open file. *name*
552 specifies the configuration value to retrieve; it may be a string which is the
553 name of a defined system value; these names are specified in a number of
554 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
555 additional names as well. The names known to the host operating system are
556 given in the ``pathconf_names`` dictionary. For configuration variables not
557 included in that mapping, passing an integer for *name* is also accepted.
558 Availability: Macintosh, Unix.
559
560 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
561 specific value for *name* is not supported by the host system, even if it is
562 included in ``pathconf_names``, an :exc:`OSError` is raised with
563 :const:`errno.EINVAL` for the error number.
564
565
566.. function:: fstat(fd)
567
568 Return status for file descriptor *fd*, like :func:`stat`. Availability:
569 Macintosh, Unix, Windows.
570
571
572.. function:: fstatvfs(fd)
573
574 Return information about the filesystem containing the file associated with file
575 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
576
577
578.. function:: fsync(fd)
579
580 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
581 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
582
583 If you're starting with a Python file object *f*, first do ``f.flush()``, and
584 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
585 with *f* are written to disk. Availability: Macintosh, Unix, and Windows
586 starting in 2.2.3.
587
588
589.. function:: ftruncate(fd, length)
590
591 Truncate the file corresponding to file descriptor *fd*, so that it is at most
592 *length* bytes in size. Availability: Macintosh, Unix.
593
594
595.. function:: isatty(fd)
596
597 Return ``True`` if the file descriptor *fd* is open and connected to a
598 tty(-like) device, else ``False``. Availability: Macintosh, Unix.
599
600
601.. function:: lseek(fd, pos, how)
602
603 Set the current position of file descriptor *fd* to position *pos*, modified by
604 *how*: ``0`` to set the position relative to the beginning of the file; ``1`` to
605 set it relative to the current position; ``2`` to set it relative to the end of
606 the file. Availability: Macintosh, Unix, Windows.
607
608
609.. function:: open(file, flags[, mode])
610
611 Open the file *file* and set various flags according to *flags* and possibly its
612 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
613 current umask value is first masked out. Return the file descriptor for the
614 newly opened file. Availability: Macintosh, Unix, Windows.
615
616 For a description of the flag and mode values, see the C run-time documentation;
617 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
618 this module too (see below).
619
620 .. note::
621
622 This function is intended for low-level I/O. For normal usage, use the built-in
623 function :func:`open`, which returns a "file object" with :meth:`read` and
624 :meth:`write` methods (and many more). To wrap a file descriptor in a "file
625 object", use :func:`fdopen`.
626
627
628.. function:: openpty()
629
630 .. index:: module: pty
631
632 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
633 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
634 approach, use the :mod:`pty` module. Availability: Macintosh, Some flavors of
635 Unix.
636
637
638.. function:: pipe()
639
640 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
641 and writing, respectively. Availability: Macintosh, Unix, Windows.
642
643
644.. function:: read(fd, n)
645
646 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
647 bytes read. If the end of the file referred to by *fd* has been reached, an
648 empty string is returned. Availability: Macintosh, Unix, Windows.
649
650 .. note::
651
652 This function is intended for low-level I/O and must be applied to a file
653 descriptor as returned by :func:`open` or :func:`pipe`. To read a "file object"
654 returned by the built-in function :func:`open` or by :func:`popen` or
655 :func:`fdopen`, or ``sys.stdin``, use its :meth:`read` or :meth:`readline`
656 methods.
657
658
659.. function:: tcgetpgrp(fd)
660
661 Return the process group associated with the terminal given by *fd* (an open
662 file descriptor as returned by :func:`open`). Availability: Macintosh, Unix.
663
664
665.. function:: tcsetpgrp(fd, pg)
666
667 Set the process group associated with the terminal given by *fd* (an open file
668 descriptor as returned by :func:`open`) to *pg*. Availability: Macintosh, Unix.
669
670
671.. function:: ttyname(fd)
672
673 Return a string which specifies the terminal device associated with
Georg Brandlbb75e4e2007-10-21 10:46:24 +0000674 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Georg Brandl8ec7f652007-08-15 14:28:01 +0000675 exception is raised. Availability:Macintosh, Unix.
676
677
678.. function:: write(fd, str)
679
680 Write the string *str* to file descriptor *fd*. Return the number of bytes
681 actually written. Availability: Macintosh, Unix, Windows.
682
683 .. note::
684
685 This function is intended for low-level I/O and must be applied to a file
686 descriptor as returned by :func:`open` or :func:`pipe`. To write a "file
687 object" returned by the built-in function :func:`open` or by :func:`popen` or
688 :func:`fdopen`, or ``sys.stdout`` or ``sys.stderr``, use its :meth:`write`
689 method.
690
691The following data items are available for use in constructing the *flags*
692parameter to the :func:`open` function. Some items will not be available on all
693platforms. For descriptions of their availability and use, consult
694:manpage:`open(2)`.
695
696
697.. data:: O_RDONLY
698 O_WRONLY
699 O_RDWR
700 O_APPEND
701 O_CREAT
702 O_EXCL
703 O_TRUNC
704
705 Options for the *flag* argument to the :func:`open` function. These can be
706 bit-wise OR'd together. Availability: Macintosh, Unix, Windows.
707
708
709.. data:: O_DSYNC
710 O_RSYNC
711 O_SYNC
712 O_NDELAY
713 O_NONBLOCK
714 O_NOCTTY
715 O_SHLOCK
716 O_EXLOCK
717
718 More options for the *flag* argument to the :func:`open` function. Availability:
719 Macintosh, Unix.
720
721
722.. data:: O_BINARY
Georg Brandlb67da6e2007-11-24 13:56:09 +0000723 O_NOINHERIT
Georg Brandl8ec7f652007-08-15 14:28:01 +0000724 O_SHORT_LIVED
725 O_TEMPORARY
726 O_RANDOM
727 O_SEQUENTIAL
728 O_TEXT
729
730 Options for the *flag* argument to the :func:`open` function. These can be
731 bit-wise OR'd together. Availability: Windows.
732
733
Georg Brandlb67da6e2007-11-24 13:56:09 +0000734.. data:: O_DIRECT
735 O_DIRECTORY
736 O_NOFOLLOW
737 O_NOATIME
738
739 Options for the *flag* argument to the :func:`open` function. These are
740 GNU extensions and not present if they are not defined by the C library.
741
742
Georg Brandl8ec7f652007-08-15 14:28:01 +0000743.. data:: SEEK_SET
744 SEEK_CUR
745 SEEK_END
746
747 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
748 respectively. Availability: Windows, Macintosh, Unix.
749
750 .. versionadded:: 2.5
751
752
753.. _os-file-dir:
754
755Files and Directories
756---------------------
757
758
759.. function:: access(path, mode)
760
761 Use the real uid/gid to test for access to *path*. Note that most operations
762 will use the effective uid/gid, therefore this routine can be used in a
763 suid/sgid environment to test if the invoking user has the specified access to
764 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
765 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
766 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
767 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
768 information. Availability: Macintosh, Unix, Windows.
769
770 .. note::
771
772 Using :func:`access` to check if a user is authorized to e.g. open a file before
773 actually doing so using :func:`open` creates a security hole, because the user
774 might exploit the short time interval between checking and opening the file to
775 manipulate it.
776
777 .. note::
778
779 I/O operations may fail even when :func:`access` indicates that they would
780 succeed, particularly for operations on network filesystems which may have
781 permissions semantics beyond the usual POSIX permission-bit model.
782
783
784.. data:: F_OK
785
786 Value to pass as the *mode* parameter of :func:`access` to test the existence of
787 *path*.
788
789
790.. data:: R_OK
791
792 Value to include in the *mode* parameter of :func:`access` to test the
793 readability of *path*.
794
795
796.. data:: W_OK
797
798 Value to include in the *mode* parameter of :func:`access` to test the
799 writability of *path*.
800
801
802.. data:: X_OK
803
804 Value to include in the *mode* parameter of :func:`access` to determine if
805 *path* can be executed.
806
807
808.. function:: chdir(path)
809
810 .. index:: single: directory; changing
811
812 Change the current working directory to *path*. Availability: Macintosh, Unix,
813 Windows.
814
815
816.. function:: fchdir(fd)
817
818 Change the current working directory to the directory represented by the file
819 descriptor *fd*. The descriptor must refer to an opened directory, not an open
820 file. Availability: Unix.
821
822 .. versionadded:: 2.3
823
824
825.. function:: getcwd()
826
827 Return a string representing the current working directory. Availability:
828 Macintosh, Unix, Windows.
829
830
831.. function:: getcwdu()
832
833 Return a Unicode object representing the current working directory.
834 Availability: Macintosh, Unix, Windows.
835
836 .. versionadded:: 2.3
837
838
839.. function:: chflags(path, flags)
840
841 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
842 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
843
844 * ``UF_NODUMP``
845 * ``UF_IMMUTABLE``
846 * ``UF_APPEND``
847 * ``UF_OPAQUE``
848 * ``UF_NOUNLINK``
849 * ``SF_ARCHIVED``
850 * ``SF_IMMUTABLE``
851 * ``SF_APPEND``
852 * ``SF_NOUNLINK``
853 * ``SF_SNAPSHOT``
854
855 Availability: Macintosh, Unix.
856
857 .. versionadded:: 2.6
858
859
860.. function:: chroot(path)
861
862 Change the root directory of the current process to *path*. Availability:
863 Macintosh, Unix.
864
865 .. versionadded:: 2.2
866
867
868.. function:: chmod(path, mode)
869
870 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
871 following values (as defined in the :mod:`stat` module) or bitwise or-ed
872 combinations of them:
873
874
875 * ``stat.S_ISUID``
876 * ``stat.S_ISGID``
877 * ``stat.S_ENFMT``
878 * ``stat.S_ISVTX``
879 * ``stat.S_IREAD``
880 * ``stat.S_IWRITE``
881 * ``stat.S_IEXEC``
882 * ``stat.S_IRWXU``
883 * ``stat.S_IRUSR``
884 * ``stat.S_IWUSR``
885 * ``stat.S_IXUSR``
886 * ``stat.S_IRWXG``
887 * ``stat.S_IRGRP``
888 * ``stat.S_IWGRP``
889 * ``stat.S_IXGRP``
890 * ``stat.S_IRWXO``
891 * ``stat.S_IROTH``
892 * ``stat.S_IWOTH``
893 * ``stat.S_IXOTH``
894
895 Availability: Macintosh, Unix, Windows.
896
897 .. note::
898
899 Although Windows supports :func:`chmod`, you can only set the file's read-only
900 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
901 constants or a corresponding integer value). All other bits are
902 ignored.
903
904
905.. function:: chown(path, uid, gid)
906
907 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
908 one of the ids unchanged, set it to -1. Availability: Macintosh, Unix.
909
910
911.. function:: lchflags(path, flags)
912
913 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
914 follow symbolic links. Availability: Unix.
915
916 .. versionadded:: 2.6
917
918
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000919.. function:: lchmod(path, mode)
920
921 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
922 affects the symlink rather than the target. See the docs for :func:`chmod`
923 for possible values of *mode*. Availability: Unix.
924
925 .. versionadded:: 2.6
926
927
Georg Brandl8ec7f652007-08-15 14:28:01 +0000928.. function:: lchown(path, uid, gid)
929
930 Change the owner and group id of *path* to the numeric *uid* and gid. This
931 function will not follow symbolic links. Availability: Macintosh, Unix.
932
933 .. versionadded:: 2.3
934
935
936.. function:: link(src, dst)
937
938 Create a hard link pointing to *src* named *dst*. Availability: Macintosh, Unix.
939
940
941.. function:: listdir(path)
942
943 Return a list containing the names of the entries in the directory. The list is
944 in arbitrary order. It does not include the special entries ``'.'`` and
945 ``'..'`` even if they are present in the directory. Availability: Macintosh,
946 Unix, Windows.
947
948 .. versionchanged:: 2.3
949 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
950 a list of Unicode objects.
951
952
953.. function:: lstat(path)
954
Georg Brandl03b15c62007-11-01 17:19:33 +0000955 Like :func:`stat`, but do not follow symbolic links. This is an alias for
956 :func:`stat` on platforms that do not support symbolic links, such as
957 Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000958
959
960.. function:: mkfifo(path[, mode])
961
962 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
963 *mode* is ``0666`` (octal). The current umask value is first masked out from
964 the mode. Availability: Macintosh, Unix.
965
966 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
967 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
968 rendezvous between "client" and "server" type processes: the server opens the
969 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
970 doesn't open the FIFO --- it just creates the rendezvous point.
971
972
973.. function:: mknod(filename[, mode=0600, device])
974
975 Create a filesystem node (file, device special file or named pipe) named
976 *filename*. *mode* specifies both the permissions to use and the type of node to
977 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
978 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
979 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
980 For ``stat.S_IFCHR`` and
981 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
982 :func:`os.makedev`), otherwise it is ignored.
983
984 .. versionadded:: 2.3
985
986
987.. function:: major(device)
988
989 Extracts the device major number from a raw device number (usually the
990 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
991
992 .. versionadded:: 2.3
993
994
995.. function:: minor(device)
996
997 Extracts the device minor number from a raw device number (usually the
998 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
999
1000 .. versionadded:: 2.3
1001
1002
1003.. function:: makedev(major, minor)
1004
1005 Composes a raw device number from the major and minor device numbers.
1006
1007 .. versionadded:: 2.3
1008
1009
1010.. function:: mkdir(path[, mode])
1011
1012 Create a directory named *path* with numeric mode *mode*. The default *mode* is
1013 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
1014 current umask value is first masked out. Availability: Macintosh, Unix, Windows.
1015
Mark Summerfieldac3d4292007-11-02 08:24:59 +00001016 It is also possible to create temporary directories; see the
1017 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1018
Georg Brandl8ec7f652007-08-15 14:28:01 +00001019
1020.. function:: makedirs(path[, mode])
1021
1022 .. index::
1023 single: directory; creating
1024 single: UNC paths; and os.makedirs()
1025
1026 Recursive directory creation function. Like :func:`mkdir`, but makes all
1027 intermediate-level directories needed to contain the leaf directory. Throws an
1028 :exc:`error` exception if the leaf directory already exists or cannot be
1029 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
1030 ignored. Where it is used, the current umask value is first masked out.
1031
1032 .. note::
1033
1034 :func:`makedirs` will become confused if the path elements to create include
1035 *os.pardir*.
1036
1037 .. versionadded:: 1.5.2
1038
1039 .. versionchanged:: 2.3
1040 This function now handles UNC paths correctly.
1041
1042
1043.. function:: pathconf(path, name)
1044
1045 Return system configuration information relevant to a named file. *name*
1046 specifies the configuration value to retrieve; it may be a string which is the
1047 name of a defined system value; these names are specified in a number of
1048 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1049 additional names as well. The names known to the host operating system are
1050 given in the ``pathconf_names`` dictionary. For configuration variables not
1051 included in that mapping, passing an integer for *name* is also accepted.
1052 Availability: Macintosh, Unix.
1053
1054 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1055 specific value for *name* is not supported by the host system, even if it is
1056 included in ``pathconf_names``, an :exc:`OSError` is raised with
1057 :const:`errno.EINVAL` for the error number.
1058
1059
1060.. data:: pathconf_names
1061
1062 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1063 the integer values defined for those names by the host operating system. This
1064 can be used to determine the set of names known to the system. Availability:
1065 Macintosh, Unix.
1066
1067
1068.. function:: readlink(path)
1069
1070 Return a string representing the path to which the symbolic link points. The
1071 result may be either an absolute or relative pathname; if it is relative, it may
1072 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1073 result)``.
1074
1075 .. versionchanged:: 2.6
1076 If the *path* is a Unicode object the result will also be a Unicode object.
1077
1078 Availability: Macintosh, Unix.
1079
1080
1081.. function:: remove(path)
1082
1083 Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
1084 :func:`rmdir` below to remove a directory. This is identical to the
1085 :func:`unlink` function documented below. On Windows, attempting to remove a
1086 file that is in use causes an exception to be raised; on Unix, the directory
1087 entry is removed but the storage allocated to the file is not made available
1088 until the original file is no longer in use. Availability: Macintosh, Unix,
1089 Windows.
1090
1091
1092.. function:: removedirs(path)
1093
1094 .. index:: single: directory; deleting
1095
1096 Removes directories recursively. Works like :func:`rmdir` except that, if the
1097 leaf directory is successfully removed, :func:`removedirs` tries to
1098 successively remove every parent directory mentioned in *path* until an error
1099 is raised (which is ignored, because it generally means that a parent directory
1100 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1101 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1102 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1103 successfully removed.
1104
1105 .. versionadded:: 1.5.2
1106
1107
1108.. function:: rename(src, dst)
1109
1110 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1111 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
1112 be removed silently if the user has permission. The operation may fail on some
1113 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1114 the renaming will be an atomic operation (this is a POSIX requirement). On
1115 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1116 file; there may be no way to implement an atomic rename when *dst* names an
1117 existing file. Availability: Macintosh, Unix, Windows.
1118
1119
1120.. function:: renames(old, new)
1121
1122 Recursive directory or file renaming function. Works like :func:`rename`, except
1123 creation of any intermediate directories needed to make the new pathname good is
1124 attempted first. After the rename, directories corresponding to rightmost path
1125 segments of the old name will be pruned away using :func:`removedirs`.
1126
1127 .. versionadded:: 1.5.2
1128
1129 .. note::
1130
1131 This function can fail with the new directory structure made if you lack
1132 permissions needed to remove the leaf directory or file.
1133
1134
1135.. function:: rmdir(path)
1136
1137 Remove the directory *path*. Availability: Macintosh, Unix, Windows.
1138
1139
1140.. function:: stat(path)
1141
1142 Perform a :cfunc:`stat` system call on the given path. The return value is an
1143 object whose attributes correspond to the members of the :ctype:`stat`
1144 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1145 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
1146 :attr:`st_uid` (user ID of owner), :attr:`st_gid` (group ID of owner),
1147 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1148 access), :attr:`st_mtime` (time of most recent content modification),
1149 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1150 Unix, or the time of creation on Windows)::
1151
1152 >>> import os
1153 >>> statinfo = os.stat('somefile.txt')
1154 >>> statinfo
1155 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1156 >>> statinfo.st_size
1157 926L
1158 >>>
1159
1160 .. versionchanged:: 2.3
1161 If :func:`stat_float_times` returns true, the time values are floats, measuring
1162 seconds. Fractions of a second may be reported if the system supports that. On
1163 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1164 discussion.
1165
1166 On some Unix systems (such as Linux), the following attributes may also be
1167 available: :attr:`st_blocks` (number of blocks allocated for file),
1168 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1169 inode device). :attr:`st_flags` (user defined flags for file).
1170
1171 On other Unix systems (such as FreeBSD), the following attributes may be
1172 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1173 (file generation number), :attr:`st_birthtime` (time of file creation).
1174
1175 On Mac OS systems, the following attributes may also be available:
1176 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1177
1178 On RISCOS systems, the following attributes are also available: :attr:`st_ftype`
1179 (file type), :attr:`st_attrs` (attributes), :attr:`st_obtype` (object type).
1180
1181 .. index:: module: stat
1182
1183 For backward compatibility, the return value of :func:`stat` is also accessible
1184 as a tuple of at least 10 integers giving the most important (and portable)
1185 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1186 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1187 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1188 :attr:`st_ctime`. More items may be added at the end by some implementations.
1189 The standard module :mod:`stat` defines functions and constants that are useful
1190 for extracting information from a :ctype:`stat` structure. (On Windows, some
1191 items are filled with dummy values.)
1192
1193 .. note::
1194
1195 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1196 :attr:`st_ctime` members depends on the operating system and the file system.
1197 For example, on Windows systems using the FAT or FAT32 file systems,
1198 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1199 resolution. See your operating system documentation for details.
1200
1201 Availability: Macintosh, Unix, Windows.
1202
1203 .. versionchanged:: 2.2
1204 Added access to values as attributes of the returned object.
1205
1206 .. versionchanged:: 2.5
1207 Added st_gen, st_birthtime.
1208
1209
1210.. function:: stat_float_times([newvalue])
1211
1212 Determine whether :class:`stat_result` represents time stamps as float objects.
1213 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1214 ``False``, future calls return ints. If *newvalue* is omitted, return the
1215 current setting.
1216
1217 For compatibility with older Python versions, accessing :class:`stat_result` as
1218 a tuple always returns integers.
1219
1220 .. versionchanged:: 2.5
1221 Python now returns float values by default. Applications which do not work
1222 correctly with floating point time stamps can use this function to restore the
1223 old behaviour.
1224
1225 The resolution of the timestamps (that is the smallest possible fraction)
1226 depends on the system. Some systems only support second resolution; on these
1227 systems, the fraction will always be zero.
1228
1229 It is recommended that this setting is only changed at program startup time in
1230 the *__main__* module; libraries should never change this setting. If an
1231 application uses a library that works incorrectly if floating point time stamps
1232 are processed, this application should turn the feature off until the library
1233 has been corrected.
1234
1235
1236.. function:: statvfs(path)
1237
1238 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1239 an object whose attributes describe the filesystem on the given path, and
1240 correspond to the members of the :ctype:`statvfs` structure, namely:
1241 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1242 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1243 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1244
1245 .. index:: module: statvfs
1246
1247 For backward compatibility, the return value is also accessible as a tuple whose
1248 values correspond to the attributes, in the order given above. The standard
1249 module :mod:`statvfs` defines constants that are useful for extracting
1250 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1251 this remains useful when writing code that needs to work with versions of Python
1252 that don't support accessing the fields as attributes.
1253
1254 .. versionchanged:: 2.2
1255 Added access to values as attributes of the returned object.
1256
1257
1258.. function:: symlink(src, dst)
1259
1260 Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
1261
1262
1263.. function:: tempnam([dir[, prefix]])
1264
1265 Return a unique path name that is reasonable for creating a temporary file.
1266 This will be an absolute path that names a potential directory entry in the
1267 directory *dir* or a common location for temporary files if *dir* is omitted or
1268 ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
1269 to the filename. Applications are responsible for properly creating and
1270 managing files created using paths returned by :func:`tempnam`; no automatic
1271 cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
1272 overrides *dir*, while on Windows the :envvar:`TMP` is used. The specific
1273 behavior of this function depends on the C library implementation; some aspects
1274 are underspecified in system documentation.
1275
1276 .. warning::
1277
1278 Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1279 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1280
1281 Availability: Macintosh, Unix, Windows.
1282
1283
1284.. function:: tmpnam()
1285
1286 Return a unique path name that is reasonable for creating a temporary file.
1287 This will be an absolute path that names a potential directory entry in a common
1288 location for temporary files. Applications are responsible for properly
1289 creating and managing files created using paths returned by :func:`tmpnam`; no
1290 automatic cleanup is provided.
1291
1292 .. warning::
1293
1294 Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1295 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1296
1297 Availability: Unix, Windows. This function probably shouldn't be used on
1298 Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1299 name in the root directory of the current drive, and that's generally a poor
1300 location for a temp file (depending on privileges, you may not even be able to
1301 open a file using this name).
1302
1303
1304.. data:: TMP_MAX
1305
1306 The maximum number of unique names that :func:`tmpnam` will generate before
1307 reusing names.
1308
1309
1310.. function:: unlink(path)
1311
1312 Remove the file *path*. This is the same function as :func:`remove`; the
1313 :func:`unlink` name is its traditional Unix name. Availability: Macintosh, Unix,
1314 Windows.
1315
1316
1317.. function:: utime(path, times)
1318
1319 Set the access and modified times of the file specified by *path*. If *times* is
1320 ``None``, then the file's access and modified times are set to the current time.
1321 Otherwise, *times* must be a 2-tuple of numbers, of the form ``(atime, mtime)``
1322 which is used to set the access and modified times, respectively. Whether a
1323 directory can be given for *path* depends on whether the operating system
1324 implements directories as files (for example, Windows does not). Note that the
1325 exact times you set here may not be returned by a subsequent :func:`stat` call,
1326 depending on the resolution with which your operating system records access and
1327 modification times; see :func:`stat`.
1328
1329 .. versionchanged:: 2.0
1330 Added support for ``None`` for *times*.
1331
1332 Availability: Macintosh, Unix, Windows.
1333
1334
1335.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1336
1337 .. index::
1338 single: directory; walking
1339 single: directory; traversal
1340
1341 :func:`walk` generates the file names in a directory tree, by walking the tree
1342 either top down or bottom up. For each directory in the tree rooted at directory
1343 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1344 filenames)``.
1345
1346 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1347 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1348 *filenames* is a list of the names of the non-directory files in *dirpath*.
1349 Note that the names in the lists contain no path components. To get a full path
1350 (which begins with *top*) to a file or directory in *dirpath*, do
1351 ``os.path.join(dirpath, name)``.
1352
1353 If optional argument *topdown* is true or not specified, the triple for a
1354 directory is generated before the triples for any of its subdirectories
1355 (directories are generated top down). If *topdown* is false, the triple for a
1356 directory is generated after the triples for all of its subdirectories
1357 (directories are generated bottom up).
1358
1359 When *topdown* is true, the caller can modify the *dirnames* list in-place
1360 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1361 recurse into the subdirectories whose names remain in *dirnames*; this can be
1362 used to prune the search, impose a specific order of visiting, or even to inform
1363 :func:`walk` about directories the caller creates or renames before it resumes
1364 :func:`walk` again. Modifying *dirnames* when *topdown* is false is
1365 ineffective, because in bottom-up mode the directories in *dirnames* are
1366 generated before *dirpath* itself is generated.
1367
1368 By default errors from the ``os.listdir()`` call are ignored. If optional
1369 argument *onerror* is specified, it should be a function; it will be called with
1370 one argument, an :exc:`OSError` instance. It can report the error to continue
1371 with the walk, or raise the exception to abort the walk. Note that the filename
1372 is available as the ``filename`` attribute of the exception object.
1373
1374 By default, :func:`walk` will not walk down into symbolic links that resolve to
1375 directories. Set *followlinks* to True to visit directories pointed to by
1376 symlinks, on systems that support them.
1377
1378 .. versionadded:: 2.6
1379 The *followlinks* parameter.
1380
1381 .. note::
1382
1383 Be aware that setting *followlinks* to true can lead to infinite recursion if a
1384 link points to a parent directory of itself. :func:`walk` does not keep track of
1385 the directories it visited already.
1386
1387 .. note::
1388
1389 If you pass a relative pathname, don't change the current working directory
1390 between resumptions of :func:`walk`. :func:`walk` never changes the current
1391 directory, and assumes that its caller doesn't either.
1392
1393 This example displays the number of bytes taken by non-directory files in each
1394 directory under the starting directory, except that it doesn't look under any
1395 CVS subdirectory::
1396
1397 import os
1398 from os.path import join, getsize
1399 for root, dirs, files in os.walk('python/Lib/email'):
1400 print root, "consumes",
1401 print sum(getsize(join(root, name)) for name in files),
1402 print "bytes in", len(files), "non-directory files"
1403 if 'CVS' in dirs:
1404 dirs.remove('CVS') # don't visit CVS directories
1405
1406 In the next example, walking the tree bottom up is essential: :func:`rmdir`
1407 doesn't allow deleting a directory before the directory is empty::
1408
1409 # Delete everything reachable from the directory named in 'top',
1410 # assuming there are no symbolic links.
1411 # CAUTION: This is dangerous! For example, if top == '/', it
1412 # could delete all your disk files.
1413 import os
1414 for root, dirs, files in os.walk(top, topdown=False):
1415 for name in files:
1416 os.remove(os.path.join(root, name))
1417 for name in dirs:
1418 os.rmdir(os.path.join(root, name))
1419
1420 .. versionadded:: 2.3
1421
1422
1423.. _os-process:
1424
1425Process Management
1426------------------
1427
1428These functions may be used to create and manage processes.
1429
1430The various :func:`exec\*` functions take a list of arguments for the new
1431program loaded into the process. In each case, the first of these arguments is
1432passed to the new program as its own name rather than as an argument a user may
1433have typed on a command line. For the C programmer, this is the ``argv[0]``
1434passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1435['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1436to be ignored.
1437
1438
1439.. function:: abort()
1440
1441 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1442 behavior is to produce a core dump; on Windows, the process immediately returns
1443 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1444 to register a handler for :const:`SIGABRT` will behave differently.
1445 Availability: Macintosh, Unix, Windows.
1446
1447
1448.. function:: execl(path, arg0, arg1, ...)
1449 execle(path, arg0, arg1, ..., env)
1450 execlp(file, arg0, arg1, ...)
1451 execlpe(file, arg0, arg1, ..., env)
1452 execv(path, args)
1453 execve(path, args, env)
1454 execvp(file, args)
1455 execvpe(file, args, env)
1456
1457 These functions all execute a new program, replacing the current process; they
1458 do not return. On Unix, the new executable is loaded into the current process,
1459 and will have the same process ID as the caller. Errors will be reported as
1460 :exc:`OSError` exceptions.
1461
1462 The ``'l'`` and ``'v'`` variants of the :func:`exec\*` functions differ in how
1463 command-line arguments are passed. The ``'l'`` variants are perhaps the easiest
1464 to work with if the number of parameters is fixed when the code is written; the
1465 individual parameters simply become additional parameters to the :func:`execl\*`
1466 functions. The ``'v'`` variants are good when the number of parameters is
1467 variable, with the arguments being passed in a list or tuple as the *args*
1468 parameter. In either case, the arguments to the child process should start with
1469 the name of the command being run, but this is not enforced.
1470
1471 The variants which include a ``'p'`` near the end (:func:`execlp`,
1472 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1473 :envvar:`PATH` environment variable to locate the program *file*. When the
1474 environment is being replaced (using one of the :func:`exec\*e` variants,
1475 discussed in the next paragraph), the new environment is used as the source of
1476 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1477 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1478 locate the executable; *path* must contain an appropriate absolute or relative
1479 path.
1480
1481 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
1482 that these all end in ``'e'``), the *env* parameter must be a mapping which is
1483 used to define the environment variables for the new process; the :func:`execl`,
1484 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1485 inherit the environment of the current process. Availability: Macintosh, Unix,
1486 Windows.
1487
1488
1489.. function:: _exit(n)
1490
1491 Exit to the system with status *n*, without calling cleanup handlers, flushing
1492 stdio buffers, etc. Availability: Macintosh, Unix, Windows.
1493
1494 .. note::
1495
1496 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1497 be used in the child process after a :func:`fork`.
1498
1499The following exit codes are a defined, and can be used with :func:`_exit`,
1500although they are not required. These are typically used for system programs
1501written in Python, such as a mail server's external command delivery program.
1502
1503.. note::
1504
1505 Some of these may not be available on all Unix platforms, since there is some
1506 variation. These constants are defined where they are defined by the underlying
1507 platform.
1508
1509
1510.. data:: EX_OK
1511
1512 Exit code that means no error occurred. Availability: Macintosh, Unix.
1513
1514 .. versionadded:: 2.3
1515
1516
1517.. data:: EX_USAGE
1518
1519 Exit code that means the command was used incorrectly, such as when the wrong
1520 number of arguments are given. Availability: Macintosh, Unix.
1521
1522 .. versionadded:: 2.3
1523
1524
1525.. data:: EX_DATAERR
1526
1527 Exit code that means the input data was incorrect. Availability: Macintosh,
1528 Unix.
1529
1530 .. versionadded:: 2.3
1531
1532
1533.. data:: EX_NOINPUT
1534
1535 Exit code that means an input file did not exist or was not readable.
1536 Availability: Macintosh, Unix.
1537
1538 .. versionadded:: 2.3
1539
1540
1541.. data:: EX_NOUSER
1542
1543 Exit code that means a specified user did not exist. Availability: Macintosh,
1544 Unix.
1545
1546 .. versionadded:: 2.3
1547
1548
1549.. data:: EX_NOHOST
1550
1551 Exit code that means a specified host did not exist. Availability: Macintosh,
1552 Unix.
1553
1554 .. versionadded:: 2.3
1555
1556
1557.. data:: EX_UNAVAILABLE
1558
1559 Exit code that means that a required service is unavailable. Availability:
1560 Macintosh, Unix.
1561
1562 .. versionadded:: 2.3
1563
1564
1565.. data:: EX_SOFTWARE
1566
1567 Exit code that means an internal software error was detected. Availability:
1568 Macintosh, Unix.
1569
1570 .. versionadded:: 2.3
1571
1572
1573.. data:: EX_OSERR
1574
1575 Exit code that means an operating system error was detected, such as the
1576 inability to fork or create a pipe. Availability: Macintosh, Unix.
1577
1578 .. versionadded:: 2.3
1579
1580
1581.. data:: EX_OSFILE
1582
1583 Exit code that means some system file did not exist, could not be opened, or had
1584 some other kind of error. Availability: Macintosh, Unix.
1585
1586 .. versionadded:: 2.3
1587
1588
1589.. data:: EX_CANTCREAT
1590
1591 Exit code that means a user specified output file could not be created.
1592 Availability: Macintosh, Unix.
1593
1594 .. versionadded:: 2.3
1595
1596
1597.. data:: EX_IOERR
1598
1599 Exit code that means that an error occurred while doing I/O on some file.
1600 Availability: Macintosh, Unix.
1601
1602 .. versionadded:: 2.3
1603
1604
1605.. data:: EX_TEMPFAIL
1606
1607 Exit code that means a temporary failure occurred. This indicates something
1608 that may not really be an error, such as a network connection that couldn't be
1609 made during a retryable operation. Availability: Macintosh, Unix.
1610
1611 .. versionadded:: 2.3
1612
1613
1614.. data:: EX_PROTOCOL
1615
1616 Exit code that means that a protocol exchange was illegal, invalid, or not
1617 understood. Availability: Macintosh, Unix.
1618
1619 .. versionadded:: 2.3
1620
1621
1622.. data:: EX_NOPERM
1623
1624 Exit code that means that there were insufficient permissions to perform the
1625 operation (but not intended for file system problems). Availability: Macintosh,
1626 Unix.
1627
1628 .. versionadded:: 2.3
1629
1630
1631.. data:: EX_CONFIG
1632
1633 Exit code that means that some kind of configuration error occurred.
1634 Availability: Macintosh, Unix.
1635
1636 .. versionadded:: 2.3
1637
1638
1639.. data:: EX_NOTFOUND
1640
1641 Exit code that means something like "an entry was not found". Availability:
1642 Macintosh, Unix.
1643
1644 .. versionadded:: 2.3
1645
1646
1647.. function:: fork()
1648
1649 Fork a child process. Return ``0`` in the child, the child's process id in the
1650 parent. Availability: Macintosh, Unix.
1651
1652
1653.. function:: forkpty()
1654
1655 Fork a child process, using a new pseudo-terminal as the child's controlling
1656 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1657 new child's process id in the parent, and *fd* is the file descriptor of the
1658 master end of the pseudo-terminal. For a more portable approach, use the
1659 :mod:`pty` module. Availability: Macintosh, Some flavors of Unix.
1660
1661
1662.. function:: kill(pid, sig)
1663
1664 .. index::
1665 single: process; killing
1666 single: process; signalling
1667
1668 Send signal *sig* to the process *pid*. Constants for the specific signals
1669 available on the host platform are defined in the :mod:`signal` module.
1670 Availability: Macintosh, Unix.
1671
1672
1673.. function:: killpg(pgid, sig)
1674
1675 .. index::
1676 single: process; killing
1677 single: process; signalling
1678
1679 Send the signal *sig* to the process group *pgid*. Availability: Macintosh,
1680 Unix.
1681
1682 .. versionadded:: 2.3
1683
1684
1685.. function:: nice(increment)
1686
1687 Add *increment* to the process's "niceness". Return the new niceness.
1688 Availability: Macintosh, Unix.
1689
1690
1691.. function:: plock(op)
1692
1693 Lock program segments into memory. The value of *op* (defined in
1694 ``<sys/lock.h>``) determines which segments are locked. Availability: Macintosh,
1695 Unix.
1696
1697
1698.. function:: popen(...)
1699 popen2(...)
1700 popen3(...)
1701 popen4(...)
1702 :noindex:
1703
1704 Run child processes, returning opened pipes for communications. These functions
1705 are described in section :ref:`os-newstreams`.
1706
1707
1708.. function:: spawnl(mode, path, ...)
1709 spawnle(mode, path, ..., env)
1710 spawnlp(mode, file, ...)
1711 spawnlpe(mode, file, ..., env)
1712 spawnv(mode, path, args)
1713 spawnve(mode, path, args, env)
1714 spawnvp(mode, file, args)
1715 spawnvpe(mode, file, args, env)
1716
1717 Execute the program *path* in a new process.
1718
1719 (Note that the :mod:`subprocess` module provides more powerful facilities for
1720 spawning new processes and retrieving their results; using that module is
1721 preferable to using these functions.)
1722
1723 If *mode* is :const:`P_NOWAIT`, this function returns the process ID of the new
1724 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1725 exits normally, or ``-signal``, where *signal* is the signal that killed the
1726 process. On Windows, the process ID will actually be the process handle, so can
1727 be used with the :func:`waitpid` function.
1728
1729 The ``'l'`` and ``'v'`` variants of the :func:`spawn\*` functions differ in how
1730 command-line arguments are passed. The ``'l'`` variants are perhaps the easiest
1731 to work with if the number of parameters is fixed when the code is written; the
1732 individual parameters simply become additional parameters to the
1733 :func:`spawnl\*` functions. The ``'v'`` variants are good when the number of
1734 parameters is variable, with the arguments being passed in a list or tuple as
1735 the *args* parameter. In either case, the arguments to the child process must
1736 start with the name of the command being run.
1737
1738 The variants which include a second ``'p'`` near the end (:func:`spawnlp`,
1739 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1740 :envvar:`PATH` environment variable to locate the program *file*. When the
1741 environment is being replaced (using one of the :func:`spawn\*e` variants,
1742 discussed in the next paragraph), the new environment is used as the source of
1743 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1744 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1745 :envvar:`PATH` variable to locate the executable; *path* must contain an
1746 appropriate absolute or relative path.
1747
1748 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
1749 (note that these all end in ``'e'``), the *env* parameter must be a mapping
1750 which is used to define the environment variables for the new process; the
1751 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1752 the new process to inherit the environment of the current process.
1753
1754 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1755 equivalent::
1756
1757 import os
1758 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1759
1760 L = ['cp', 'index.html', '/dev/null']
1761 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1762
1763 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1764 and :func:`spawnvpe` are not available on Windows.
1765
1766 .. versionadded:: 1.6
1767
1768
1769.. data:: P_NOWAIT
1770 P_NOWAITO
1771
1772 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1773 functions. If either of these values is given, the :func:`spawn\*` functions
1774 will return as soon as the new process has been created, with the process ID as
1775 the return value. Availability: Macintosh, Unix, Windows.
1776
1777 .. versionadded:: 1.6
1778
1779
1780.. data:: P_WAIT
1781
1782 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1783 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1784 return until the new process has run to completion and will return the exit code
1785 of the process the run is successful, or ``-signal`` if a signal kills the
1786 process. Availability: Macintosh, Unix, Windows.
1787
1788 .. versionadded:: 1.6
1789
1790
1791.. data:: P_DETACH
1792 P_OVERLAY
1793
1794 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1795 functions. These are less portable than those listed above. :const:`P_DETACH`
1796 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1797 console of the calling process. If :const:`P_OVERLAY` is used, the current
1798 process will be replaced; the :func:`spawn\*` function will not return.
1799 Availability: Windows.
1800
1801 .. versionadded:: 1.6
1802
1803
1804.. function:: startfile(path[, operation])
1805
1806 Start a file with its associated application.
1807
1808 When *operation* is not specified or ``'open'``, this acts like double-clicking
1809 the file in Windows Explorer, or giving the file name as an argument to the
1810 :program:`start` command from the interactive command shell: the file is opened
1811 with whatever application (if any) its extension is associated.
1812
1813 When another *operation* is given, it must be a "command verb" that specifies
1814 what should be done with the file. Common verbs documented by Microsoft are
1815 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1816 ``'find'`` (to be used on directories).
1817
1818 :func:`startfile` returns as soon as the associated application is launched.
1819 There is no option to wait for the application to close, and no way to retrieve
1820 the application's exit status. The *path* parameter is relative to the current
1821 directory. If you want to use an absolute path, make sure the first character
1822 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1823 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1824 the path is properly encoded for Win32. Availability: Windows.
1825
1826 .. versionadded:: 2.0
1827
1828 .. versionadded:: 2.5
1829 The *operation* parameter.
1830
1831
1832.. function:: system(command)
1833
1834 Execute the command (a string) in a subshell. This is implemented by calling
1835 the Standard C function :cfunc:`system`, and has the same limitations. Changes
1836 to ``posix.environ``, ``sys.stdin``, etc. are not reflected in the environment
1837 of the executed command.
1838
1839 On Unix, the return value is the exit status of the process encoded in the
1840 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1841 of the return value of the C :cfunc:`system` function, so the return value of
1842 the Python function is system-dependent.
1843
1844 On Windows, the return value is that returned by the system shell after running
1845 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1846 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1847 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1848 the command run; on systems using a non-native shell, consult your shell
1849 documentation.
1850
1851 Availability: Macintosh, Unix, Windows.
1852
1853 The :mod:`subprocess` module provides more powerful facilities for spawning new
1854 processes and retrieving their results; using that module is preferable to using
1855 this function.
1856
1857
1858.. function:: times()
1859
1860 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1861 other) times, in seconds. The items are: user time, system time, children's
1862 user time, children's system time, and elapsed real time since a fixed point in
1863 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
1864 corresponding Windows Platform API documentation. Availability: Macintosh, Unix,
1865 Windows.
1866
1867
1868.. function:: wait()
1869
1870 Wait for completion of a child process, and return a tuple containing its pid
1871 and exit status indication: a 16-bit number, whose low byte is the signal number
1872 that killed the process, and whose high byte is the exit status (if the signal
1873 number is zero); the high bit of the low byte is set if a core file was
1874 produced. Availability: Macintosh, Unix.
1875
1876
1877.. function:: waitpid(pid, options)
1878
1879 The details of this function differ on Unix and Windows.
1880
1881 On Unix: Wait for completion of a child process given by process id *pid*, and
1882 return a tuple containing its process id and exit status indication (encoded as
1883 for :func:`wait`). The semantics of the call are affected by the value of the
1884 integer *options*, which should be ``0`` for normal operation.
1885
1886 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1887 that specific process. If *pid* is ``0``, the request is for the status of any
1888 child in the process group of the current process. If *pid* is ``-1``, the
1889 request pertains to any child of the current process. If *pid* is less than
1890 ``-1``, status is requested for any process in the process group ``-pid`` (the
1891 absolute value of *pid*).
1892
1893 On Windows: Wait for completion of a process given by process handle *pid*, and
1894 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1895 (shifting makes cross-platform use of the function easier). A *pid* less than or
1896 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1897 value of integer *options* has no effect. *pid* can refer to any process whose
1898 id is known, not necessarily a child process. The :func:`spawn` functions called
1899 with :const:`P_NOWAIT` return suitable process handles.
1900
1901
1902.. function:: wait3([options])
1903
1904 Similar to :func:`waitpid`, except no process id argument is given and a
1905 3-element tuple containing the child's process id, exit status indication, and
1906 resource usage information is returned. Refer to :mod:`resource`.\
1907 :func:`getrusage` for details on resource usage information. The option
1908 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1909 Availability: Unix.
1910
1911 .. versionadded:: 2.5
1912
1913
1914.. function:: wait4(pid, options)
1915
1916 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1917 process id, exit status indication, and resource usage information is returned.
1918 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1919 information. The arguments to :func:`wait4` are the same as those provided to
1920 :func:`waitpid`. Availability: Unix.
1921
1922 .. versionadded:: 2.5
1923
1924
1925.. data:: WNOHANG
1926
1927 The option for :func:`waitpid` to return immediately if no child process status
1928 is available immediately. The function returns ``(0, 0)`` in this case.
1929 Availability: Macintosh, Unix.
1930
1931
1932.. data:: WCONTINUED
1933
1934 This option causes child processes to be reported if they have been continued
1935 from a job control stop since their status was last reported. Availability: Some
1936 Unix systems.
1937
1938 .. versionadded:: 2.3
1939
1940
1941.. data:: WUNTRACED
1942
1943 This option causes child processes to be reported if they have been stopped but
1944 their current state has not been reported since they were stopped. Availability:
1945 Macintosh, Unix.
1946
1947 .. versionadded:: 2.3
1948
1949The following functions take a process status code as returned by
1950:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1951used to determine the disposition of a process.
1952
1953
1954.. function:: WCOREDUMP(status)
1955
1956 Returns ``True`` if a core dump was generated for the process, otherwise it
1957 returns ``False``. Availability: Macintosh, Unix.
1958
1959 .. versionadded:: 2.3
1960
1961
1962.. function:: WIFCONTINUED(status)
1963
1964 Returns ``True`` if the process has been continued from a job control stop,
1965 otherwise it returns ``False``. Availability: Unix.
1966
1967 .. versionadded:: 2.3
1968
1969
1970.. function:: WIFSTOPPED(status)
1971
1972 Returns ``True`` if the process has been stopped, otherwise it returns
1973 ``False``. Availability: Unix.
1974
1975
1976.. function:: WIFSIGNALED(status)
1977
1978 Returns ``True`` if the process exited due to a signal, otherwise it returns
1979 ``False``. Availability: Macintosh, Unix.
1980
1981
1982.. function:: WIFEXITED(status)
1983
1984 Returns ``True`` if the process exited using the :manpage:`exit(2)` system call,
1985 otherwise it returns ``False``. Availability: Macintosh, Unix.
1986
1987
1988.. function:: WEXITSTATUS(status)
1989
1990 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1991 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
1992 Availability: Macintosh, Unix.
1993
1994
1995.. function:: WSTOPSIG(status)
1996
1997 Return the signal which caused the process to stop. Availability: Macintosh,
1998 Unix.
1999
2000
2001.. function:: WTERMSIG(status)
2002
2003 Return the signal which caused the process to exit. Availability: Macintosh,
2004 Unix.
2005
2006
2007.. _os-path:
2008
2009Miscellaneous System Information
2010--------------------------------
2011
2012
2013.. function:: confstr(name)
2014
2015 Return string-valued system configuration values. *name* specifies the
2016 configuration value to retrieve; it may be a string which is the name of a
2017 defined system value; these names are specified in a number of standards (POSIX,
2018 Unix 95, Unix 98, and others). Some platforms define additional names as well.
2019 The names known to the host operating system are given as the keys of the
2020 ``confstr_names`` dictionary. For configuration variables not included in that
2021 mapping, passing an integer for *name* is also accepted. Availability:
2022 Macintosh, Unix.
2023
2024 If the configuration value specified by *name* isn't defined, ``None`` is
2025 returned.
2026
2027 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2028 specific value for *name* is not supported by the host system, even if it is
2029 included in ``confstr_names``, an :exc:`OSError` is raised with
2030 :const:`errno.EINVAL` for the error number.
2031
2032
2033.. data:: confstr_names
2034
2035 Dictionary mapping names accepted by :func:`confstr` to the integer values
2036 defined for those names by the host operating system. This can be used to
2037 determine the set of names known to the system. Availability: Macintosh, Unix.
2038
2039
2040.. function:: getloadavg()
2041
2042 Return the number of processes in the system run queue averaged over the last 1,
2043 5, and 15 minutes or raises :exc:`OSError` if the load average was
2044 unobtainable.
2045
2046 .. versionadded:: 2.3
2047
2048
2049.. function:: sysconf(name)
2050
2051 Return integer-valued system configuration values. If the configuration value
2052 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2053 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2054 provides information on the known names is given by ``sysconf_names``.
2055 Availability: Macintosh, Unix.
2056
2057
2058.. data:: sysconf_names
2059
2060 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2061 defined for those names by the host operating system. This can be used to
2062 determine the set of names known to the system. Availability: Macintosh, Unix.
2063
2064The follow data values are used to support path manipulation operations. These
2065are defined for all platforms.
2066
2067Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2068
2069
2070.. data:: curdir
2071
2072 The constant string used by the operating system to refer to the current
2073 directory. For example: ``'.'`` for POSIX or ``':'`` for Mac OS 9. Also
2074 available via :mod:`os.path`.
2075
2076
2077.. data:: pardir
2078
2079 The constant string used by the operating system to refer to the parent
2080 directory. For example: ``'..'`` for POSIX or ``'::'`` for Mac OS 9. Also
2081 available via :mod:`os.path`.
2082
2083
2084.. data:: sep
2085
2086 The character used by the operating system to separate pathname components, for
2087 example, ``'/'`` for POSIX or ``':'`` for Mac OS 9. Note that knowing this is
2088 not sufficient to be able to parse or concatenate pathnames --- use
2089 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2090 useful. Also available via :mod:`os.path`.
2091
2092
2093.. data:: altsep
2094
2095 An alternative character used by the operating system to separate pathname
2096 components, or ``None`` if only one separator character exists. This is set to
2097 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2098 :mod:`os.path`.
2099
2100
2101.. data:: extsep
2102
2103 The character which separates the base filename from the extension; for example,
2104 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2105
2106 .. versionadded:: 2.2
2107
2108
2109.. data:: pathsep
2110
2111 The character conventionally used by the operating system to separate search
2112 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2113 Windows. Also available via :mod:`os.path`.
2114
2115
2116.. data:: defpath
2117
2118 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
2119 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
2120
2121
2122.. data:: linesep
2123
2124 The string used to separate (or, rather, terminate) lines on the current
2125 platform. This may be a single character, such as ``'\n'`` for POSIX or
2126 ``'\r'`` for Mac OS, or multiple characters, for example, ``'\r\n'`` for
2127 Windows. Do not use *os.linesep* as a line terminator when writing files opened
2128 in text mode (the default); use a single ``'\n'`` instead, on all platforms.
2129
2130
2131.. data:: devnull
2132
2133 The file path of the null device. For example: ``'/dev/null'`` for POSIX or
2134 ``'Dev:Nul'`` for Mac OS 9. Also available via :mod:`os.path`.
2135
2136 .. versionadded:: 2.4
2137
2138
2139.. _os-miscfunc:
2140
2141Miscellaneous Functions
2142-----------------------
2143
2144
2145.. function:: urandom(n)
2146
2147 Return a string of *n* random bytes suitable for cryptographic use.
2148
2149 This function returns random bytes from an OS-specific randomness source. The
2150 returned data should be unpredictable enough for cryptographic applications,
2151 though its exact quality depends on the OS implementation. On a UNIX-like
2152 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
2153 If a randomness source is not found, :exc:`NotImplementedError` will be raised.
2154
2155 .. versionadded:: 2.4
2156