1 :mod:`os` --- Miscellaneous operating system interfaces
2 =======================================================
5 :synopsis: Miscellaneous operating system interfaces.
8 This module provides a portable way of using operating system dependent
9 functionality. If you just want to read or write a file see :func:`open`, if
10 you want to manipulate paths, see the :mod:`os.path` module, and if you want to
11 read all the lines in all the files on the command line see the :mod:`fileinput`
12 module. For creating temporary files and directories see the :mod:`tempfile`
13 module, and for high-level file and directory handling see the :mod:`shutil`
16 Notes on the availability of these functions:
18 * The design of all built-in operating system dependent modules of Python is
19 such that as long as the same functionality is available, it uses the same
20 interface; for example, the function ``os.stat(path)`` returns stat
21 information about *path* in the same format (which happens to have originated
22 with the POSIX interface).
24 * Extensions peculiar to a particular operating system are also available
25 through the :mod:`os` module, but using them is of course a threat to
28 * An "Availability: Unix" note means that this function is commonly found on
29 Unix systems. It does not make any claims about its existence on a specific
32 * If not separately noted, all functions that claim "Availability: Unix" are
33 supported on Mac OS X, which builds on a Unix core.
37 All functions in this module raise :exc:`OSError` in the case of invalid or
38 inaccessible file names and paths, or other arguments that have the correct
39 type, but are not accepted by the operating system.
44 An alias for the built-in :exc:`OSError` exception.
49 The name of the operating system dependent module imported. The following
50 names have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``,
51 ``'os2'``, ``'ce'``, ``'java'``, ``'riscos'``.
59 These functions and data items provide information and operate on the current
65 A mapping object representing the string environment. For example,
66 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
67 and is equivalent to ``getenv("HOME")`` in C.
69 This mapping is captured the first time the :mod:`os` module is imported,
70 typically during Python startup as part of processing :file:`site.py`. Changes
71 to the environment made after this time are not reflected in ``os.environ``,
72 except for changes made by modifying ``os.environ`` directly.
74 If the platform supports the :func:`putenv` function, this mapping may be used
75 to modify the environment as well as query the environment. :func:`putenv` will
76 be called automatically when the mapping is modified.
80 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
81 to modify ``os.environ``.
85 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
86 cause memory leaks. Refer to the system documentation for
89 If :func:`putenv` is not provided, a modified copy of this mapping may be
90 passed to the appropriate process-creation functions to cause child processes
91 to use a modified environment.
93 If the platform supports the :func:`unsetenv` function, you can delete items in
94 this mapping to unset environment variables. :func:`unsetenv` will be called
95 automatically when an item is deleted from ``os.environ``, and when
96 one of the :meth:`pop` or :meth:`clear` methods is called.
98 .. versionchanged:: 2.6
99 Also unset environment variables when calling :meth:`os.environ.clear`
100 and :meth:`os.environ.pop`.
103 .. function:: chdir(path)
108 These functions are described in :ref:`os-file-dir`.
111 .. function:: ctermid()
113 Return the filename corresponding to the controlling terminal of the process.
117 .. function:: getegid()
119 Return the effective group id of the current process. This corresponds to the
120 "set id" bit on the file being executed in the current process. Availability:
124 .. function:: geteuid()
126 .. index:: single: user; effective id
128 Return the current process's effective user id. Availability: Unix.
131 .. function:: getgid()
133 .. index:: single: process; group
135 Return the real group id of the current process. Availability: Unix.
138 .. function:: getgroups()
140 Return list of supplemental group ids associated with the current process.
144 .. function:: initgroups(username, gid)
146 Call the system initgroups() to initialize the group access list with all of
147 the groups of which the specified username is a member, plus the specified
148 group id. Availability: Unix.
150 .. versionadded:: 2.7
153 .. function:: getlogin()
155 Return the name of the user logged in on the controlling terminal of the
156 process. For most purposes, it is more useful to use the environment variable
157 :envvar:`LOGNAME` to find out who the user is, or
158 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
159 effective user id. Availability: Unix.
162 .. function:: getpgid(pid)
164 Return the process group id of the process with process id *pid*. If *pid* is 0,
165 the process group id of the current process is returned. Availability: Unix.
167 .. versionadded:: 2.3
170 .. function:: getpgrp()
172 .. index:: single: process; group
174 Return the id of the current process group. Availability: Unix.
177 .. function:: getpid()
179 .. index:: single: process; id
181 Return the current process id. Availability: Unix, Windows.
184 .. function:: getppid()
186 .. index:: single: process; id of parent
188 Return the parent's process id. Availability: Unix.
191 .. function:: getresuid()
193 Return a tuple (ruid, euid, suid) denoting the current process's
194 real, effective, and saved user ids. Availability: Unix.
196 .. versionadded:: 2.7
199 .. function:: getresgid()
201 Return a tuple (rgid, egid, sgid) denoting the current process's
202 real, effective, and saved user ids. Availability: Unix.
204 .. versionadded:: 2.7
207 .. function:: getuid()
209 .. index:: single: user; id
211 Return the current process's user id. Availability: Unix.
214 .. function:: getenv(varname[, value])
216 Return the value of the environment variable *varname* if it exists, or *value*
217 if it doesn't. *value* defaults to ``None``. Availability: most flavors of
221 .. function:: putenv(varname, value)
223 .. index:: single: environment variables; setting
225 Set the environment variable named *varname* to the string *value*. Such
226 changes to the environment affect subprocesses started with :func:`os.system`,
227 :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
232 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
233 cause memory leaks. Refer to the system documentation for putenv.
235 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
236 automatically translated into corresponding calls to :func:`putenv`; however,
237 calls to :func:`putenv` don't update ``os.environ``, so it is actually
238 preferable to assign to items of ``os.environ``.
241 .. function:: setegid(egid)
243 Set the current process's effective group id. Availability: Unix.
246 .. function:: seteuid(euid)
248 Set the current process's effective user id. Availability: Unix.
251 .. function:: setgid(gid)
253 Set the current process' group id. Availability: Unix.
256 .. function:: setgroups(groups)
258 Set the list of supplemental group ids associated with the current process to
259 *groups*. *groups* must be a sequence, and each element must be an integer
260 identifying a group. This operation is typically available only to the superuser.
263 .. versionadded:: 2.2
266 .. function:: setpgrp()
268 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
269 which version is implemented (if any). See the Unix manual for the semantics.
273 .. function:: setpgid(pid, pgrp)
275 Call the system call :cfunc:`setpgid` to set the process group id of the
276 process with id *pid* to the process group with id *pgrp*. See the Unix manual
277 for the semantics. Availability: Unix.
280 .. function:: setregid(rgid, egid)
282 Set the current process's real and effective group ids. Availability: Unix.
285 .. function:: setresgid(rgid, egid, sgid)
287 Set the current process's real, effective, and saved group ids.
290 .. versionadded:: 2.7
293 .. function:: setresuid(ruid, euid, suid)
295 Set the current process's real, effective, and saved user ids.
298 .. versionadded:: 2.7
301 .. function:: setreuid(ruid, euid)
303 Set the current process's real and effective user ids. Availability: Unix.
306 .. function:: getsid(pid)
308 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
311 .. versionadded:: 2.4
314 .. function:: setsid()
316 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
320 .. function:: setuid(uid)
322 .. index:: single: user; id, setting
324 Set the current process's user id. Availability: Unix.
327 .. placed in this section since it relates to errno.... a little weak
328 .. function:: strerror(code)
330 Return the error message corresponding to the error code in *code*.
331 On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
332 error number, :exc:`ValueError` is raised. Availability: Unix, Windows.
335 .. function:: umask(mask)
337 Set the current numeric umask and return the previous umask. Availability:
341 .. function:: uname()
344 single: gethostname() (in module socket)
345 single: gethostbyaddr() (in module socket)
347 Return a 5-tuple containing information identifying the current operating
348 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
349 machine)``. Some systems truncate the nodename to 8 characters or to the
350 leading component; a better way to get the hostname is
351 :func:`socket.gethostname` or even
352 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
356 .. function:: unsetenv(varname)
358 .. index:: single: environment variables; deleting
360 Unset (delete) the environment variable named *varname*. Such changes to the
361 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
362 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
364 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
365 automatically translated into a corresponding call to :func:`unsetenv`; however,
366 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
367 preferable to delete items of ``os.environ``.
375 These functions create new file objects. (See also :func:`open`.)
378 .. function:: fdopen(fd[, mode[, bufsize]])
380 .. index:: single: I/O control; buffering
382 Return an open file object connected to the file descriptor *fd*. The *mode*
383 and *bufsize* arguments have the same meaning as the corresponding arguments to
384 the built-in :func:`open` function. Availability: Unix, Windows.
386 .. versionchanged:: 2.3
387 When specified, the *mode* argument must now start with one of the letters
388 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
390 .. versionchanged:: 2.5
391 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
392 set on the file descriptor (which the :cfunc:`fdopen` implementation already
393 does on most platforms).
396 .. function:: popen(command[, mode[, bufsize]])
398 Open a pipe to or from *command*. The return value is an open file object
399 connected to the pipe, which can be read or written depending on whether *mode*
400 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
401 the corresponding argument to the built-in :func:`open` function. The exit
402 status of the command (encoded in the format specified for :func:`wait`) is
403 available as the return value of the :meth:`~file.close` method of the file object,
404 except that when the exit status is zero (termination without errors), ``None``
405 is returned. Availability: Unix, Windows.
408 This function is obsolete. Use the :mod:`subprocess` module. Check
409 especially the :ref:`subprocess-replacements` section.
411 .. versionchanged:: 2.0
412 This function worked unreliably under Windows in earlier versions of Python.
413 This was due to the use of the :cfunc:`_popen` function from the libraries
414 provided with Windows. Newer versions of Python do not use the broken
415 implementation from the Windows libraries.
418 .. function:: tmpfile()
420 Return a new file object opened in update mode (``w+b``). The file has no
421 directory entries associated with it and will be automatically deleted once
422 there are no file descriptors for the file. Availability: Unix,
425 There are a number of different :func:`popen\*` functions that provide slightly
426 different ways to create subprocesses.
429 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
432 For each of the :func:`popen\*` variants, if *bufsize* is specified, it
433 specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
434 string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
435 file objects should be opened in binary or text mode. The default value for
438 Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
439 case arguments will be passed directly to the program without shell intervention
440 (as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
441 (as with :func:`os.system`).
443 These methods do not make it possible to retrieve the exit status from the child
444 processes. The only way to control the input and output streams and also
445 retrieve the return codes is to use the :mod:`subprocess` module; these are only
448 For a discussion of possible deadlock conditions related to the use of these
449 functions, see :ref:`popen2-flow-control`.
452 .. function:: popen2(cmd[, mode[, bufsize]])
454 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
458 This function is obsolete. Use the :mod:`subprocess` module. Check
459 especially the :ref:`subprocess-replacements` section.
461 Availability: Unix, Windows.
463 .. versionadded:: 2.0
466 .. function:: popen3(cmd[, mode[, bufsize]])
468 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
469 child_stdout, child_stderr)``.
472 This function is obsolete. Use the :mod:`subprocess` module. Check
473 especially the :ref:`subprocess-replacements` section.
475 Availability: Unix, Windows.
477 .. versionadded:: 2.0
480 .. function:: popen4(cmd[, mode[, bufsize]])
482 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
483 child_stdout_and_stderr)``.
486 This function is obsolete. Use the :mod:`subprocess` module. Check
487 especially the :ref:`subprocess-replacements` section.
489 Availability: Unix, Windows.
491 .. versionadded:: 2.0
493 (Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
494 point of view of the child process, so *child_stdin* is the child's standard
497 This functionality is also available in the :mod:`popen2` module using functions
498 of the same names, but the return values of those functions have a different
504 File Descriptor Operations
505 --------------------------
507 These functions operate on I/O streams referenced using file descriptors.
509 File descriptors are small integers corresponding to a file that has been opened
510 by the current process. For example, standard input is usually file descriptor
511 0, standard output is 1, and standard error is 2. Further files opened by a
512 process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
513 is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
517 .. function:: close(fd)
519 Close file descriptor *fd*. Availability: Unix, Windows.
523 This function is intended for low-level I/O and must be applied to a file
524 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
525 object" returned by the built-in function :func:`open` or by :func:`popen` or
526 :func:`fdopen`, use its :meth:`~file.close` method.
529 .. function:: closerange(fd_low, fd_high)
531 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
532 ignoring errors. Availability: Unix, Windows. Equivalent to::
534 for fd in xrange(fd_low, fd_high):
540 .. versionadded:: 2.6
543 .. function:: dup(fd)
545 Return a duplicate of file descriptor *fd*. Availability: Unix,
549 .. function:: dup2(fd, fd2)
551 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
552 Availability: Unix, Windows.
555 .. function:: fchmod(fd, mode)
557 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
558 for :func:`chmod` for possible values of *mode*. Availability: Unix.
560 .. versionadded:: 2.6
563 .. function:: fchown(fd, uid, gid)
565 Change the owner and group id of the file given by *fd* to the numeric *uid*
566 and *gid*. To leave one of the ids unchanged, set it to -1.
569 .. versionadded:: 2.6
572 .. function:: fdatasync(fd)
574 Force write of file with filedescriptor *fd* to disk. Does not force update of
575 metadata. Availability: Unix.
578 This function is not available on MacOS.
581 .. function:: fpathconf(fd, name)
583 Return system configuration information relevant to an open file. *name*
584 specifies the configuration value to retrieve; it may be a string which is the
585 name of a defined system value; these names are specified in a number of
586 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
587 additional names as well. The names known to the host operating system are
588 given in the ``pathconf_names`` dictionary. For configuration variables not
589 included in that mapping, passing an integer for *name* is also accepted.
592 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
593 specific value for *name* is not supported by the host system, even if it is
594 included in ``pathconf_names``, an :exc:`OSError` is raised with
595 :const:`errno.EINVAL` for the error number.
598 .. function:: fstat(fd)
600 Return status for file descriptor *fd*, like :func:`stat`. Availability:
604 .. function:: fstatvfs(fd)
606 Return information about the filesystem containing the file associated with file
607 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
610 .. function:: fsync(fd)
612 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
613 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
615 If you're starting with a Python file object *f*, first do ``f.flush()``, and
616 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
617 with *f* are written to disk. Availability: Unix, and Windows
621 .. function:: ftruncate(fd, length)
623 Truncate the file corresponding to file descriptor *fd*, so that it is at most
624 *length* bytes in size. Availability: Unix.
627 .. function:: isatty(fd)
629 Return ``True`` if the file descriptor *fd* is open and connected to a
630 tty(-like) device, else ``False``. Availability: Unix.
633 .. function:: lseek(fd, pos, how)
635 Set the current position of file descriptor *fd* to position *pos*, modified
636 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
637 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
638 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
639 the file. Availability: Unix, Windows.
642 .. function:: open(file, flags[, mode])
644 Open the file *file* and set various flags according to *flags* and possibly its
645 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
646 current umask value is first masked out. Return the file descriptor for the
647 newly opened file. Availability: Unix, Windows.
649 For a description of the flag and mode values, see the C run-time documentation;
650 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
651 this module too (see below).
655 This function is intended for low-level I/O. For normal usage, use the
656 built-in function :func:`open`, which returns a "file object" with
657 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
658 wrap a file descriptor in a "file object", use :func:`fdopen`.
661 .. function:: openpty()
663 .. index:: module: pty
665 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
666 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
667 approach, use the :mod:`pty` module. Availability: some flavors of
673 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
674 and writing, respectively. Availability: Unix, Windows.
677 .. function:: read(fd, n)
679 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
680 bytes read. If the end of the file referred to by *fd* has been reached, an
681 empty string is returned. Availability: Unix, Windows.
685 This function is intended for low-level I/O and must be applied to a file
686 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a "file object"
687 returned by the built-in function :func:`open` or by :func:`popen` or
688 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
689 :meth:`~file.readline` methods.
692 .. function:: tcgetpgrp(fd)
694 Return the process group associated with the terminal given by *fd* (an open
695 file descriptor as returned by :func:`os.open`). Availability: Unix.
698 .. function:: tcsetpgrp(fd, pg)
700 Set the process group associated with the terminal given by *fd* (an open file
701 descriptor as returned by :func:`os.open`) to *pg*. Availability: Unix.
704 .. function:: ttyname(fd)
706 Return a string which specifies the terminal device associated with
707 file descriptor *fd*. If *fd* is not associated with a terminal device, an
708 exception is raised. Availability: Unix.
711 .. function:: write(fd, str)
713 Write the string *str* to file descriptor *fd*. Return the number of bytes
714 actually written. Availability: Unix, Windows.
718 This function is intended for low-level I/O and must be applied to a file
719 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
720 object" returned by the built-in function :func:`open` or by :func:`popen` or
721 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
722 :meth:`~file.write` method.
724 The following constants are options for the *flags* parameter to the
725 :func:`~os.open` function. They can be combined using the bitwise OR operator
726 ``|``. Some of them are not available on all platforms. For descriptions of
727 their availability and use, consult the :manpage:`open(2)` manual page on Unix
728 or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
739 These constants are available on Unix and Windows.
751 These constants are only available on Unix.
762 These constants are only available on Windows.
771 These constants are GNU extensions and not present if they are not defined by
779 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
780 respectively. Availability: Windows, Unix.
782 .. versionadded:: 2.5
787 Files and Directories
788 ---------------------
790 .. function:: access(path, mode)
792 Use the real uid/gid to test for access to *path*. Note that most operations
793 will use the effective uid/gid, therefore this routine can be used in a
794 suid/sgid environment to test if the invoking user has the specified access to
795 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
796 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
797 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
798 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
799 information. Availability: Unix, Windows.
803 Using :func:`access` to check if a user is authorized to e.g. open a file
804 before actually doing so using :func:`open` creates a security hole,
805 because the user might exploit the short time interval between checking
806 and opening the file to manipulate it.
810 I/O operations may fail even when :func:`access` indicates that they would
811 succeed, particularly for operations on network filesystems which may have
812 permissions semantics beyond the usual POSIX permission-bit model.
817 Value to pass as the *mode* parameter of :func:`access` to test the existence of
823 Value to include in the *mode* parameter of :func:`access` to test the
824 readability of *path*.
829 Value to include in the *mode* parameter of :func:`access` to test the
830 writability of *path*.
835 Value to include in the *mode* parameter of :func:`access` to determine if
836 *path* can be executed.
839 .. function:: chdir(path)
841 .. index:: single: directory; changing
843 Change the current working directory to *path*. Availability: Unix,
847 .. function:: fchdir(fd)
849 Change the current working directory to the directory represented by the file
850 descriptor *fd*. The descriptor must refer to an opened directory, not an open
851 file. Availability: Unix.
853 .. versionadded:: 2.3
856 .. function:: getcwd()
858 Return a string representing the current working directory. Availability:
862 .. function:: getcwdu()
864 Return a Unicode object representing the current working directory.
865 Availability: Unix, Windows.
867 .. versionadded:: 2.3
870 .. function:: chflags(path, flags)
872 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
873 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
888 .. versionadded:: 2.6
891 .. function:: chroot(path)
893 Change the root directory of the current process to *path*. Availability:
896 .. versionadded:: 2.2
899 .. function:: chmod(path, mode)
901 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
902 following values (as defined in the :mod:`stat` module) or bitwise ORed
903 combinations of them:
906 * :data:`stat.S_ISUID`
907 * :data:`stat.S_ISGID`
908 * :data:`stat.S_ENFMT`
909 * :data:`stat.S_ISVTX`
910 * :data:`stat.S_IREAD`
911 * :data:`stat.S_IWRITE`
912 * :data:`stat.S_IEXEC`
913 * :data:`stat.S_IRWXU`
914 * :data:`stat.S_IRUSR`
915 * :data:`stat.S_IWUSR`
916 * :data:`stat.S_IXUSR`
917 * :data:`stat.S_IRWXG`
918 * :data:`stat.S_IRGRP`
919 * :data:`stat.S_IWGRP`
920 * :data:`stat.S_IXGRP`
921 * :data:`stat.S_IRWXO`
922 * :data:`stat.S_IROTH`
923 * :data:`stat.S_IWOTH`
924 * :data:`stat.S_IXOTH`
926 Availability: Unix, Windows.
930 Although Windows supports :func:`chmod`, you can only set the file's read-only
931 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
932 constants or a corresponding integer value). All other bits are
936 .. function:: chown(path, uid, gid)
938 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
939 one of the ids unchanged, set it to -1. Availability: Unix.
942 .. function:: lchflags(path, flags)
944 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
945 follow symbolic links. Availability: Unix.
947 .. versionadded:: 2.6
950 .. function:: lchmod(path, mode)
952 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
953 affects the symlink rather than the target. See the docs for :func:`chmod`
954 for possible values of *mode*. Availability: Unix.
956 .. versionadded:: 2.6
959 .. function:: lchown(path, uid, gid)
961 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
962 function will not follow symbolic links. Availability: Unix.
964 .. versionadded:: 2.3
967 .. function:: link(source, link_name)
969 Create a hard link pointing to *source* named *link_name*. Availability:
973 .. function:: listdir(path)
975 Return a list containing the names of the entries in the directory given by
976 *path*. The list is in arbitrary order. It does not include the special
977 entries ``'.'`` and ``'..'`` even if they are present in the
978 directory. Availability: Unix, Windows.
980 .. versionchanged:: 2.3
981 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
982 a list of Unicode objects. Undecodable filenames will still be returned as
986 .. function:: lstat(path)
988 Like :func:`stat`, but do not follow symbolic links. This is an alias for
989 :func:`stat` on platforms that do not support symbolic links, such as
993 .. function:: mkfifo(path[, mode])
995 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
996 *mode* is ``0666`` (octal). The current umask value is first masked out from
997 the mode. Availability: Unix.
999 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
1000 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
1001 rendezvous between "client" and "server" type processes: the server opens the
1002 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
1003 doesn't open the FIFO --- it just creates the rendezvous point.
1006 .. function:: mknod(filename[, mode=0600, device])
1008 Create a filesystem node (file, device special file or named pipe) named
1009 *filename*. *mode* specifies both the permissions to use and the type of node to
1010 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
1011 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
1012 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
1013 For ``stat.S_IFCHR`` and
1014 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
1015 :func:`os.makedev`), otherwise it is ignored.
1017 .. versionadded:: 2.3
1020 .. function:: major(device)
1022 Extract the device major number from a raw device number (usually the
1023 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
1025 .. versionadded:: 2.3
1028 .. function:: minor(device)
1030 Extract the device minor number from a raw device number (usually the
1031 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
1033 .. versionadded:: 2.3
1036 .. function:: makedev(major, minor)
1038 Compose a raw device number from the major and minor device numbers.
1040 .. versionadded:: 2.3
1043 .. function:: mkdir(path[, mode])
1045 Create a directory named *path* with numeric mode *mode*. The default *mode* is
1046 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
1047 current umask value is first masked out. Availability: Unix, Windows.
1049 It is also possible to create temporary directories; see the
1050 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1053 .. function:: makedirs(path[, mode])
1056 single: directory; creating
1057 single: UNC paths; and os.makedirs()
1059 Recursive directory creation function. Like :func:`mkdir`, but makes all
1060 intermediate-level directories needed to contain the leaf directory. Throws an
1061 :exc:`error` exception if the leaf directory already exists or cannot be
1062 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
1063 ignored. Where it is used, the current umask value is first masked out.
1067 :func:`makedirs` will become confused if the path elements to create include
1070 .. versionadded:: 1.5.2
1072 .. versionchanged:: 2.3
1073 This function now handles UNC paths correctly.
1076 .. function:: pathconf(path, name)
1078 Return system configuration information relevant to a named file. *name*
1079 specifies the configuration value to retrieve; it may be a string which is the
1080 name of a defined system value; these names are specified in a number of
1081 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1082 additional names as well. The names known to the host operating system are
1083 given in the ``pathconf_names`` dictionary. For configuration variables not
1084 included in that mapping, passing an integer for *name* is also accepted.
1087 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1088 specific value for *name* is not supported by the host system, even if it is
1089 included in ``pathconf_names``, an :exc:`OSError` is raised with
1090 :const:`errno.EINVAL` for the error number.
1093 .. data:: pathconf_names
1095 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1096 the integer values defined for those names by the host operating system. This
1097 can be used to determine the set of names known to the system. Availability:
1101 .. function:: readlink(path)
1103 Return a string representing the path to which the symbolic link points. The
1104 result may be either an absolute or relative pathname; if it is relative, it may
1105 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1108 .. versionchanged:: 2.6
1109 If the *path* is a Unicode object the result will also be a Unicode object.
1114 .. function:: remove(path)
1116 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
1117 raised; see :func:`rmdir` below to remove a directory. This is identical to
1118 the :func:`unlink` function documented below. On Windows, attempting to
1119 remove a file that is in use causes an exception to be raised; on Unix, the
1120 directory entry is removed but the storage allocated to the file is not made
1121 available until the original file is no longer in use. Availability: Unix,
1125 .. function:: removedirs(path)
1127 .. index:: single: directory; deleting
1129 Remove directories recursively. Works like :func:`rmdir` except that, if the
1130 leaf directory is successfully removed, :func:`removedirs` tries to
1131 successively remove every parent directory mentioned in *path* until an error
1132 is raised (which is ignored, because it generally means that a parent directory
1133 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1134 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1135 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1136 successfully removed.
1138 .. versionadded:: 1.5.2
1141 .. function:: rename(src, dst)
1143 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1144 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
1145 be replaced silently if the user has permission. The operation may fail on some
1146 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1147 the renaming will be an atomic operation (this is a POSIX requirement). On
1148 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1149 file; there may be no way to implement an atomic rename when *dst* names an
1150 existing file. Availability: Unix, Windows.
1153 .. function:: renames(old, new)
1155 Recursive directory or file renaming function. Works like :func:`rename`, except
1156 creation of any intermediate directories needed to make the new pathname good is
1157 attempted first. After the rename, directories corresponding to rightmost path
1158 segments of the old name will be pruned away using :func:`removedirs`.
1160 .. versionadded:: 1.5.2
1164 This function can fail with the new directory structure made if you lack
1165 permissions needed to remove the leaf directory or file.
1168 .. function:: rmdir(path)
1170 Remove (delete) the directory *path*. Only works when the directory is
1171 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
1172 directory trees, :func:`shutil.rmtree` can be used. Availability: Unix,
1176 .. function:: stat(path)
1178 Perform a :cfunc:`stat` system call on the given path. The return value is an
1179 object whose attributes correspond to the members of the :ctype:`stat`
1180 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1181 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
1182 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
1183 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1184 access), :attr:`st_mtime` (time of most recent content modification),
1185 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1186 Unix, or the time of creation on Windows)::
1189 >>> statinfo = os.stat('somefile.txt')
1191 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1192 >>> statinfo.st_size
1196 .. versionchanged:: 2.3
1197 If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
1198 seconds. Fractions of a second may be reported if the system supports that. On
1199 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1202 On some Unix systems (such as Linux), the following attributes may also be
1203 available: :attr:`st_blocks` (number of blocks allocated for file),
1204 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1205 inode device). :attr:`st_flags` (user defined flags for file).
1207 On other Unix systems (such as FreeBSD), the following attributes may be
1208 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1209 (file generation number), :attr:`st_birthtime` (time of file creation).
1211 On Mac OS systems, the following attributes may also be available:
1212 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1214 On RISCOS systems, the following attributes are also available: :attr:`st_ftype`
1215 (file type), :attr:`st_attrs` (attributes), :attr:`st_obtype` (object type).
1217 .. index:: module: stat
1219 For backward compatibility, the return value of :func:`stat` is also accessible
1220 as a tuple of at least 10 integers giving the most important (and portable)
1221 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1222 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1223 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1224 :attr:`st_ctime`. More items may be added at the end by some implementations.
1225 The standard module :mod:`stat` defines functions and constants that are useful
1226 for extracting information from a :ctype:`stat` structure. (On Windows, some
1227 items are filled with dummy values.)
1231 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1232 :attr:`st_ctime` members depends on the operating system and the file system.
1233 For example, on Windows systems using the FAT or FAT32 file systems,
1234 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1235 resolution. See your operating system documentation for details.
1237 Availability: Unix, Windows.
1239 .. versionchanged:: 2.2
1240 Added access to values as attributes of the returned object.
1242 .. versionchanged:: 2.5
1243 Added :attr:`st_gen` and :attr:`st_birthtime`.
1246 .. function:: stat_float_times([newvalue])
1248 Determine whether :class:`stat_result` represents time stamps as float objects.
1249 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1250 ``False``, future calls return ints. If *newvalue* is omitted, return the
1253 For compatibility with older Python versions, accessing :class:`stat_result` as
1254 a tuple always returns integers.
1256 .. versionchanged:: 2.5
1257 Python now returns float values by default. Applications which do not work
1258 correctly with floating point time stamps can use this function to restore the
1261 The resolution of the timestamps (that is the smallest possible fraction)
1262 depends on the system. Some systems only support second resolution; on these
1263 systems, the fraction will always be zero.
1265 It is recommended that this setting is only changed at program startup time in
1266 the *__main__* module; libraries should never change this setting. If an
1267 application uses a library that works incorrectly if floating point time stamps
1268 are processed, this application should turn the feature off until the library
1272 .. function:: statvfs(path)
1274 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1275 an object whose attributes describe the filesystem on the given path, and
1276 correspond to the members of the :ctype:`statvfs` structure, namely:
1277 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1278 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1279 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1281 .. index:: module: statvfs
1283 For backward compatibility, the return value is also accessible as a tuple whose
1284 values correspond to the attributes, in the order given above. The standard
1285 module :mod:`statvfs` defines constants that are useful for extracting
1286 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1287 this remains useful when writing code that needs to work with versions of Python
1288 that don't support accessing the fields as attributes.
1290 .. versionchanged:: 2.2
1291 Added access to values as attributes of the returned object.
1294 .. function:: symlink(source, link_name)
1296 Create a symbolic link pointing to *source* named *link_name*. Availability:
1300 .. function:: tempnam([dir[, prefix]])
1302 Return a unique path name that is reasonable for creating a temporary file.
1303 This will be an absolute path that names a potential directory entry in the
1304 directory *dir* or a common location for temporary files if *dir* is omitted or
1305 ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
1306 to the filename. Applications are responsible for properly creating and
1307 managing files created using paths returned by :func:`tempnam`; no automatic
1308 cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
1309 overrides *dir*, while on Windows :envvar:`TMP` is used. The specific
1310 behavior of this function depends on the C library implementation; some aspects
1311 are underspecified in system documentation.
1315 Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1316 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1318 Availability: Unix, Windows.
1321 .. function:: tmpnam()
1323 Return a unique path name that is reasonable for creating a temporary file.
1324 This will be an absolute path that names a potential directory entry in a common
1325 location for temporary files. Applications are responsible for properly
1326 creating and managing files created using paths returned by :func:`tmpnam`; no
1327 automatic cleanup is provided.
1331 Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1332 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1334 Availability: Unix, Windows. This function probably shouldn't be used on
1335 Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1336 name in the root directory of the current drive, and that's generally a poor
1337 location for a temp file (depending on privileges, you may not even be able to
1338 open a file using this name).
1343 The maximum number of unique names that :func:`tmpnam` will generate before
1347 .. function:: unlink(path)
1349 Remove (delete) the file *path*. This is the same function as
1350 :func:`remove`; the :func:`unlink` name is its traditional Unix
1351 name. Availability: Unix, Windows.
1354 .. function:: utime(path, times)
1356 Set the access and modified times of the file specified by *path*. If *times*
1357 is ``None``, then the file's access and modified times are set to the current
1358 time. (The effect is similar to running the Unix program :program:`touch` on
1359 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1360 ``(atime, mtime)`` which is used to set the access and modified times,
1361 respectively. Whether a directory can be given for *path* depends on whether
1362 the operating system implements directories as files (for example, Windows
1363 does not). Note that the exact times you set here may not be returned by a
1364 subsequent :func:`stat` call, depending on the resolution with which your
1365 operating system records access and modification times; see :func:`stat`.
1367 .. versionchanged:: 2.0
1368 Added support for ``None`` for *times*.
1370 Availability: Unix, Windows.
1373 .. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1376 single: directory; walking
1377 single: directory; traversal
1379 Generate the file names in a directory tree by walking the tree
1380 either top-down or bottom-up. For each directory in the tree rooted at directory
1381 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1384 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1385 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1386 *filenames* is a list of the names of the non-directory files in *dirpath*.
1387 Note that the names in the lists contain no path components. To get a full path
1388 (which begins with *top*) to a file or directory in *dirpath*, do
1389 ``os.path.join(dirpath, name)``.
1391 If optional argument *topdown* is ``True`` or not specified, the triple for a
1392 directory is generated before the triples for any of its subdirectories
1393 (directories are generated top-down). If *topdown* is ``False``, the triple for a
1394 directory is generated after the triples for all of its subdirectories
1395 (directories are generated bottom-up).
1397 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
1398 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1399 recurse into the subdirectories whose names remain in *dirnames*; this can be
1400 used to prune the search, impose a specific order of visiting, or even to inform
1401 :func:`walk` about directories the caller creates or renames before it resumes
1402 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
1403 ineffective, because in bottom-up mode the directories in *dirnames* are
1404 generated before *dirpath* itself is generated.
1406 By default errors from the :func:`listdir` call are ignored. If optional
1407 argument *onerror* is specified, it should be a function; it will be called with
1408 one argument, an :exc:`OSError` instance. It can report the error to continue
1409 with the walk, or raise the exception to abort the walk. Note that the filename
1410 is available as the ``filename`` attribute of the exception object.
1412 By default, :func:`walk` will not walk down into symbolic links that resolve to
1413 directories. Set *followlinks* to ``True`` to visit directories pointed to by
1414 symlinks, on systems that support them.
1416 .. versionadded:: 2.6
1417 The *followlinks* parameter.
1421 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
1422 link points to a parent directory of itself. :func:`walk` does not keep track of
1423 the directories it visited already.
1427 If you pass a relative pathname, don't change the current working directory
1428 between resumptions of :func:`walk`. :func:`walk` never changes the current
1429 directory, and assumes that its caller doesn't either.
1431 This example displays the number of bytes taken by non-directory files in each
1432 directory under the starting directory, except that it doesn't look under any
1436 from os.path import join, getsize
1437 for root, dirs, files in os.walk('python/Lib/email'):
1438 print root, "consumes",
1439 print sum(getsize(join(root, name)) for name in files),
1440 print "bytes in", len(files), "non-directory files"
1442 dirs.remove('CVS') # don't visit CVS directories
1444 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
1445 doesn't allow deleting a directory before the directory is empty::
1447 # Delete everything reachable from the directory named in "top",
1448 # assuming there are no symbolic links.
1449 # CAUTION: This is dangerous! For example, if top == '/', it
1450 # could delete all your disk files.
1452 for root, dirs, files in os.walk(top, topdown=False):
1454 os.remove(os.path.join(root, name))
1456 os.rmdir(os.path.join(root, name))
1458 .. versionadded:: 2.3
1466 These functions may be used to create and manage processes.
1468 The various :func:`exec\*` functions take a list of arguments for the new
1469 program loaded into the process. In each case, the first of these arguments is
1470 passed to the new program as its own name rather than as an argument a user may
1471 have typed on a command line. For the C programmer, this is the ``argv[0]``
1472 passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1473 ['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1477 .. function:: abort()
1479 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1480 behavior is to produce a core dump; on Windows, the process immediately returns
1481 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1482 to register a handler for :const:`SIGABRT` will behave differently.
1483 Availability: Unix, Windows.
1486 .. function:: execl(path, arg0, arg1, ...)
1487 execle(path, arg0, arg1, ..., env)
1488 execlp(file, arg0, arg1, ...)
1489 execlpe(file, arg0, arg1, ..., env)
1491 execve(path, args, env)
1493 execvpe(file, args, env)
1495 These functions all execute a new program, replacing the current process; they
1496 do not return. On Unix, the new executable is loaded into the current process,
1497 and will have the same process id as the caller. Errors will be reported as
1498 :exc:`OSError` exceptions.
1500 The current process is replaced immediately. Open file objects and
1501 descriptors are not flushed, so if there may be data buffered
1502 on these open files, you should flush them using
1503 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
1504 :func:`exec\*` function.
1506 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1507 command-line arguments are passed. The "l" variants are perhaps the easiest
1508 to work with if the number of parameters is fixed when the code is written; the
1509 individual parameters simply become additional parameters to the :func:`execl\*`
1510 functions. The "v" variants are good when the number of parameters is
1511 variable, with the arguments being passed in a list or tuple as the *args*
1512 parameter. In either case, the arguments to the child process should start with
1513 the name of the command being run, but this is not enforced.
1515 The variants which include a "p" near the end (:func:`execlp`,
1516 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1517 :envvar:`PATH` environment variable to locate the program *file*. When the
1518 environment is being replaced (using one of the :func:`exec\*e` variants,
1519 discussed in the next paragraph), the new environment is used as the source of
1520 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1521 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1522 locate the executable; *path* must contain an appropriate absolute or relative
1525 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
1526 that these all end in "e"), the *env* parameter must be a mapping which is
1527 used to define the environment variables for the new process (these are used
1528 instead of the current process' environment); the functions :func:`execl`,
1529 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1530 inherit the environment of the current process.
1532 Availability: Unix, Windows.
1535 .. function:: _exit(n)
1537 Exit to the system with status *n*, without calling cleanup handlers, flushing
1538 stdio buffers, etc. Availability: Unix, Windows.
1542 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1543 be used in the child process after a :func:`fork`.
1545 The following exit codes are defined and can be used with :func:`_exit`,
1546 although they are not required. These are typically used for system programs
1547 written in Python, such as a mail server's external command delivery program.
1551 Some of these may not be available on all Unix platforms, since there is some
1552 variation. These constants are defined where they are defined by the underlying
1558 Exit code that means no error occurred. Availability: Unix.
1560 .. versionadded:: 2.3
1565 Exit code that means the command was used incorrectly, such as when the wrong
1566 number of arguments are given. Availability: Unix.
1568 .. versionadded:: 2.3
1571 .. data:: EX_DATAERR
1573 Exit code that means the input data was incorrect. Availability: Unix.
1575 .. versionadded:: 2.3
1578 .. data:: EX_NOINPUT
1580 Exit code that means an input file did not exist or was not readable.
1583 .. versionadded:: 2.3
1588 Exit code that means a specified user did not exist. Availability: Unix.
1590 .. versionadded:: 2.3
1595 Exit code that means a specified host did not exist. Availability: Unix.
1597 .. versionadded:: 2.3
1600 .. data:: EX_UNAVAILABLE
1602 Exit code that means that a required service is unavailable. Availability:
1605 .. versionadded:: 2.3
1608 .. data:: EX_SOFTWARE
1610 Exit code that means an internal software error was detected. Availability:
1613 .. versionadded:: 2.3
1618 Exit code that means an operating system error was detected, such as the
1619 inability to fork or create a pipe. Availability: Unix.
1621 .. versionadded:: 2.3
1626 Exit code that means some system file did not exist, could not be opened, or had
1627 some other kind of error. Availability: Unix.
1629 .. versionadded:: 2.3
1632 .. data:: EX_CANTCREAT
1634 Exit code that means a user specified output file could not be created.
1637 .. versionadded:: 2.3
1642 Exit code that means that an error occurred while doing I/O on some file.
1645 .. versionadded:: 2.3
1648 .. data:: EX_TEMPFAIL
1650 Exit code that means a temporary failure occurred. This indicates something
1651 that may not really be an error, such as a network connection that couldn't be
1652 made during a retryable operation. Availability: Unix.
1654 .. versionadded:: 2.3
1657 .. data:: EX_PROTOCOL
1659 Exit code that means that a protocol exchange was illegal, invalid, or not
1660 understood. Availability: Unix.
1662 .. versionadded:: 2.3
1667 Exit code that means that there were insufficient permissions to perform the
1668 operation (but not intended for file system problems). Availability: Unix.
1670 .. versionadded:: 2.3
1675 Exit code that means that some kind of configuration error occurred.
1678 .. versionadded:: 2.3
1681 .. data:: EX_NOTFOUND
1683 Exit code that means something like "an entry was not found". Availability:
1686 .. versionadded:: 2.3
1689 .. function:: fork()
1691 Fork a child process. Return ``0`` in the child and the child's process id in the
1692 parent. If an error occurs :exc:`OSError` is raised.
1694 Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
1695 known issues when using fork() from a thread.
1700 .. function:: forkpty()
1702 Fork a child process, using a new pseudo-terminal as the child's controlling
1703 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1704 new child's process id in the parent, and *fd* is the file descriptor of the
1705 master end of the pseudo-terminal. For a more portable approach, use the
1706 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
1707 Availability: some flavors of Unix.
1710 .. function:: kill(pid, sig)
1713 single: process; killing
1714 single: process; signalling
1716 Send signal *sig* to the process *pid*. Constants for the specific signals
1717 available on the host platform are defined in the :mod:`signal` module.
1721 .. function:: killpg(pgid, sig)
1724 single: process; killing
1725 single: process; signalling
1727 Send the signal *sig* to the process group *pgid*. Availability: Unix.
1729 .. versionadded:: 2.3
1732 .. function:: nice(increment)
1734 Add *increment* to the process's "niceness". Return the new niceness.
1738 .. function:: plock(op)
1740 Lock program segments into memory. The value of *op* (defined in
1741 ``<sys/lock.h>``) determines which segments are locked. Availability: Unix.
1744 .. function:: popen(...)
1750 Run child processes, returning opened pipes for communications. These functions
1751 are described in section :ref:`os-newstreams`.
1754 .. function:: spawnl(mode, path, ...)
1755 spawnle(mode, path, ..., env)
1756 spawnlp(mode, file, ...)
1757 spawnlpe(mode, file, ..., env)
1758 spawnv(mode, path, args)
1759 spawnve(mode, path, args, env)
1760 spawnvp(mode, file, args)
1761 spawnvpe(mode, file, args, env)
1763 Execute the program *path* in a new process.
1765 (Note that the :mod:`subprocess` module provides more powerful facilities for
1766 spawning new processes and retrieving their results; using that module is
1767 preferable to using these functions. Check especially the
1768 :ref:`subprocess-replacements` section.)
1770 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
1771 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1772 exits normally, or ``-signal``, where *signal* is the signal that killed the
1773 process. On Windows, the process id will actually be the process handle, so can
1774 be used with the :func:`waitpid` function.
1776 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1777 command-line arguments are passed. The "l" variants are perhaps the easiest
1778 to work with if the number of parameters is fixed when the code is written; the
1779 individual parameters simply become additional parameters to the
1780 :func:`spawnl\*` functions. The "v" variants are good when the number of
1781 parameters is variable, with the arguments being passed in a list or tuple as
1782 the *args* parameter. In either case, the arguments to the child process must
1783 start with the name of the command being run.
1785 The variants which include a second "p" near the end (:func:`spawnlp`,
1786 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1787 :envvar:`PATH` environment variable to locate the program *file*. When the
1788 environment is being replaced (using one of the :func:`spawn\*e` variants,
1789 discussed in the next paragraph), the new environment is used as the source of
1790 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1791 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1792 :envvar:`PATH` variable to locate the executable; *path* must contain an
1793 appropriate absolute or relative path.
1795 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
1796 (note that these all end in "e"), the *env* parameter must be a mapping
1797 which is used to define the environment variables for the new process (they are
1798 used instead of the current process' environment); the functions
1799 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1800 the new process to inherit the environment of the current process. Note that
1801 keys and values in the *env* dictionary must be strings; invalid keys or
1802 values will cause the function to fail, with a return value of ``127``.
1804 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1808 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1810 L = ['cp', 'index.html', '/dev/null']
1811 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1813 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1814 and :func:`spawnvpe` are not available on Windows.
1816 .. versionadded:: 1.6
1822 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1823 functions. If either of these values is given, the :func:`spawn\*` functions
1824 will return as soon as the new process has been created, with the process id as
1825 the return value. Availability: Unix, Windows.
1827 .. versionadded:: 1.6
1832 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1833 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1834 return until the new process has run to completion and will return the exit code
1835 of the process the run is successful, or ``-signal`` if a signal kills the
1836 process. Availability: Unix, Windows.
1838 .. versionadded:: 1.6
1844 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1845 functions. These are less portable than those listed above. :const:`P_DETACH`
1846 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1847 console of the calling process. If :const:`P_OVERLAY` is used, the current
1848 process will be replaced; the :func:`spawn\*` function will not return.
1849 Availability: Windows.
1851 .. versionadded:: 1.6
1854 .. function:: startfile(path[, operation])
1856 Start a file with its associated application.
1858 When *operation* is not specified or ``'open'``, this acts like double-clicking
1859 the file in Windows Explorer, or giving the file name as an argument to the
1860 :program:`start` command from the interactive command shell: the file is opened
1861 with whatever application (if any) its extension is associated.
1863 When another *operation* is given, it must be a "command verb" that specifies
1864 what should be done with the file. Common verbs documented by Microsoft are
1865 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1866 ``'find'`` (to be used on directories).
1868 :func:`startfile` returns as soon as the associated application is launched.
1869 There is no option to wait for the application to close, and no way to retrieve
1870 the application's exit status. The *path* parameter is relative to the current
1871 directory. If you want to use an absolute path, make sure the first character
1872 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1873 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1874 the path is properly encoded for Win32. Availability: Windows.
1876 .. versionadded:: 2.0
1878 .. versionadded:: 2.5
1879 The *operation* parameter.
1882 .. function:: system(command)
1884 Execute the command (a string) in a subshell. This is implemented by calling
1885 the Standard C function :cfunc:`system`, and has the same limitations.
1886 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the
1889 On Unix, the return value is the exit status of the process encoded in the
1890 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1891 of the return value of the C :cfunc:`system` function, so the return value of
1892 the Python function is system-dependent.
1894 On Windows, the return value is that returned by the system shell after running
1895 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1896 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1897 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1898 the command run; on systems using a non-native shell, consult your shell
1901 Availability: Unix, Windows.
1903 The :mod:`subprocess` module provides more powerful facilities for spawning new
1904 processes and retrieving their results; using that module is preferable to using
1905 this function. Use the :mod:`subprocess` module. Check especially the
1906 :ref:`subprocess-replacements` section.
1909 .. function:: times()
1911 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1912 other) times, in seconds. The items are: user time, system time, children's
1913 user time, children's system time, and elapsed real time since a fixed point in
1914 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
1915 corresponding Windows Platform API documentation. Availability: Unix,
1916 Windows. On Windows, only the first two items are filled, the others are zero.
1919 .. function:: wait()
1921 Wait for completion of a child process, and return a tuple containing its pid
1922 and exit status indication: a 16-bit number, whose low byte is the signal number
1923 that killed the process, and whose high byte is the exit status (if the signal
1924 number is zero); the high bit of the low byte is set if a core file was
1925 produced. Availability: Unix.
1928 .. function:: waitpid(pid, options)
1930 The details of this function differ on Unix and Windows.
1932 On Unix: Wait for completion of a child process given by process id *pid*, and
1933 return a tuple containing its process id and exit status indication (encoded as
1934 for :func:`wait`). The semantics of the call are affected by the value of the
1935 integer *options*, which should be ``0`` for normal operation.
1937 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1938 that specific process. If *pid* is ``0``, the request is for the status of any
1939 child in the process group of the current process. If *pid* is ``-1``, the
1940 request pertains to any child of the current process. If *pid* is less than
1941 ``-1``, status is requested for any process in the process group ``-pid`` (the
1942 absolute value of *pid*).
1944 An :exc:`OSError` is raised with the value of errno when the syscall
1947 On Windows: Wait for completion of a process given by process handle *pid*, and
1948 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1949 (shifting makes cross-platform use of the function easier). A *pid* less than or
1950 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1951 value of integer *options* has no effect. *pid* can refer to any process whose
1952 id is known, not necessarily a child process. The :func:`spawn` functions called
1953 with :const:`P_NOWAIT` return suitable process handles.
1956 .. function:: wait3([options])
1958 Similar to :func:`waitpid`, except no process id argument is given and a
1959 3-element tuple containing the child's process id, exit status indication, and
1960 resource usage information is returned. Refer to :mod:`resource`.\
1961 :func:`getrusage` for details on resource usage information. The option
1962 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1965 .. versionadded:: 2.5
1968 .. function:: wait4(pid, options)
1970 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1971 process id, exit status indication, and resource usage information is returned.
1972 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1973 information. The arguments to :func:`wait4` are the same as those provided to
1974 :func:`waitpid`. Availability: Unix.
1976 .. versionadded:: 2.5
1981 The option for :func:`waitpid` to return immediately if no child process status
1982 is available immediately. The function returns ``(0, 0)`` in this case.
1986 .. data:: WCONTINUED
1988 This option causes child processes to be reported if they have been continued
1989 from a job control stop since their status was last reported. Availability: Some
1992 .. versionadded:: 2.3
1997 This option causes child processes to be reported if they have been stopped but
1998 their current state has not been reported since they were stopped. Availability:
2001 .. versionadded:: 2.3
2003 The following functions take a process status code as returned by
2004 :func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
2005 used to determine the disposition of a process.
2008 .. function:: WCOREDUMP(status)
2010 Return ``True`` if a core dump was generated for the process, otherwise
2011 return ``False``. Availability: Unix.
2013 .. versionadded:: 2.3
2016 .. function:: WIFCONTINUED(status)
2018 Return ``True`` if the process has been continued from a job control stop,
2019 otherwise return ``False``. Availability: Unix.
2021 .. versionadded:: 2.3
2024 .. function:: WIFSTOPPED(status)
2026 Return ``True`` if the process has been stopped, otherwise return
2027 ``False``. Availability: Unix.
2030 .. function:: WIFSIGNALED(status)
2032 Return ``True`` if the process exited due to a signal, otherwise return
2033 ``False``. Availability: Unix.
2036 .. function:: WIFEXITED(status)
2038 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
2039 otherwise return ``False``. Availability: Unix.
2042 .. function:: WEXITSTATUS(status)
2044 If ``WIFEXITED(status)`` is true, return the integer parameter to the
2045 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
2049 .. function:: WSTOPSIG(status)
2051 Return the signal which caused the process to stop. Availability: Unix.
2054 .. function:: WTERMSIG(status)
2056 Return the signal which caused the process to exit. Availability: Unix.
2061 Miscellaneous System Information
2062 --------------------------------
2065 .. function:: confstr(name)
2067 Return string-valued system configuration values. *name* specifies the
2068 configuration value to retrieve; it may be a string which is the name of a
2069 defined system value; these names are specified in a number of standards (POSIX,
2070 Unix 95, Unix 98, and others). Some platforms define additional names as well.
2071 The names known to the host operating system are given as the keys of the
2072 ``confstr_names`` dictionary. For configuration variables not included in that
2073 mapping, passing an integer for *name* is also accepted. Availability:
2076 If the configuration value specified by *name* isn't defined, ``None`` is
2079 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2080 specific value for *name* is not supported by the host system, even if it is
2081 included in ``confstr_names``, an :exc:`OSError` is raised with
2082 :const:`errno.EINVAL` for the error number.
2085 .. data:: confstr_names
2087 Dictionary mapping names accepted by :func:`confstr` to the integer values
2088 defined for those names by the host operating system. This can be used to
2089 determine the set of names known to the system. Availability: Unix.
2092 .. function:: getloadavg()
2094 Return the number of processes in the system run queue averaged over the last
2095 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
2096 unobtainable. Availability: Unix.
2098 .. versionadded:: 2.3
2101 .. function:: sysconf(name)
2103 Return integer-valued system configuration values. If the configuration value
2104 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2105 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2106 provides information on the known names is given by ``sysconf_names``.
2110 .. data:: sysconf_names
2112 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2113 defined for those names by the host operating system. This can be used to
2114 determine the set of names known to the system. Availability: Unix.
2116 The following data values are used to support path manipulation operations. These
2117 are defined for all platforms.
2119 Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2124 The constant string used by the operating system to refer to the current
2125 directory. This is ``'.'`` for Windows and POSIX. Also available via
2131 The constant string used by the operating system to refer to the parent
2132 directory. This is ``'..'`` for Windows and POSIX. Also available via
2138 The character used by the operating system to separate pathname components.
2139 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
2140 is not sufficient to be able to parse or concatenate pathnames --- use
2141 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2142 useful. Also available via :mod:`os.path`.
2147 An alternative character used by the operating system to separate pathname
2148 components, or ``None`` if only one separator character exists. This is set to
2149 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2155 The character which separates the base filename from the extension; for example,
2156 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2158 .. versionadded:: 2.2
2163 The character conventionally used by the operating system to separate search
2164 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2165 Windows. Also available via :mod:`os.path`.
2170 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
2171 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
2176 The string used to separate (or, rather, terminate) lines on the current
2177 platform. This may be a single character, such as ``'\n'`` for POSIX, or
2178 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
2179 *os.linesep* as a line terminator when writing files opened in text mode (the
2180 default); use a single ``'\n'`` instead, on all platforms.
2185 The file path of the null device. For example: ``'/dev/null'`` for POSIX.
2186 Also available via :mod:`os.path`.
2188 .. versionadded:: 2.4
2193 Miscellaneous Functions
2194 -----------------------
2197 .. function:: urandom(n)
2199 Return a string of *n* random bytes suitable for cryptographic use.
2201 This function returns random bytes from an OS-specific randomness source. The
2202 returned data should be unpredictable enough for cryptographic applications,
2203 though its exact quality depends on the OS implementation. On a UNIX-like
2204 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
2205 If a randomness source is not found, :exc:`NotImplementedError` will be raised.
2207 .. versionadded:: 2.4