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 The design of all built-in operating system dependent modules of Python is such
17 that as long as the same functionality is available, it uses the same interface;
18 for example, the function ``os.stat(path)`` returns stat information about
19 *path* in the same format (which happens to have originated with the POSIX
22 Extensions peculiar to a particular operating system are also available through
23 the :mod:`os` module, but using them is of course a threat to portability!
27 If not separately noted, all functions that claim "Availability: Unix" are
28 supported on Mac OS X, which builds on a Unix core.
32 All functions in this module raise :exc:`OSError` in the case of invalid or
33 inaccessible file names and paths, or other arguments that have the correct
34 type, but are not accepted by the operating system.
39 An alias for the built-in :exc:`OSError` exception.
44 The name of the operating system dependent module imported. The following names
45 have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``,
46 ``'ce'``, ``'java'``, ``'riscos'``.
54 These functions and data items provide information and operate on the current
60 A mapping object representing the string environment. For example,
61 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
62 and is equivalent to ``getenv("HOME")`` in C.
64 This mapping is captured the first time the :mod:`os` module is imported,
65 typically during Python startup as part of processing :file:`site.py`. Changes
66 to the environment made after this time are not reflected in ``os.environ``,
67 except for changes made by modifying ``os.environ`` directly.
69 If the platform supports the :func:`putenv` function, this mapping may be used
70 to modify the environment as well as query the environment. :func:`putenv` will
71 be called automatically when the mapping is modified.
75 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
76 to modify ``os.environ``.
80 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
81 cause memory leaks. Refer to the system documentation for
84 If :func:`putenv` is not provided, a modified copy of this mapping may be
85 passed to the appropriate process-creation functions to cause child processes
86 to use a modified environment.
88 If the platform supports the :func:`unsetenv` function, you can delete items in
89 this mapping to unset environment variables. :func:`unsetenv` will be called
90 automatically when an item is deleted from ``os.environ``, and when
91 one of the :meth:`pop` or :meth:`clear` methods is called.
93 .. versionchanged:: 2.6
94 Also unset environment variables when calling :meth:`os.environ.clear`
95 and :meth:`os.environ.pop`.
98 .. function:: chdir(path)
103 These functions are described in :ref:`os-file-dir`.
106 .. function:: ctermid()
108 Return the filename corresponding to the controlling terminal of the process.
112 .. function:: getegid()
114 Return the effective group id of the current process. This corresponds to the
115 "set id" bit on the file being executed in the current process. Availability:
119 .. function:: geteuid()
121 .. index:: single: user; effective id
123 Return the current process's effective user id. Availability: Unix.
126 .. function:: getgid()
128 .. index:: single: process; group
130 Return the real group id of the current process. Availability: Unix.
133 .. function:: getgroups()
135 Return list of supplemental group ids associated with the current process.
139 .. function:: getlogin()
141 Return the name of the user logged in on the controlling terminal of the
142 process. For most purposes, it is more useful to use the environment variable
143 :envvar:`LOGNAME` to find out who the user is, or
144 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
145 effective user id. Availability: Unix.
148 .. function:: getpgid(pid)
150 Return the process group id of the process with process id *pid*. If *pid* is 0,
151 the process group id of the current process is returned. Availability: Unix.
153 .. versionadded:: 2.3
156 .. function:: getpgrp()
158 .. index:: single: process; group
160 Return the id of the current process group. Availability: Unix.
163 .. function:: getpid()
165 .. index:: single: process; id
167 Return the current process id. Availability: Unix, Windows.
170 .. function:: getppid()
172 .. index:: single: process; id of parent
174 Return the parent's process id. Availability: Unix.
177 .. function:: getuid()
179 .. index:: single: user; id
181 Return the current process's user id. Availability: Unix.
184 .. function:: getenv(varname[, value])
186 Return the value of the environment variable *varname* if it exists, or *value*
187 if it doesn't. *value* defaults to ``None``. Availability: most flavors of
191 .. function:: putenv(varname, value)
193 .. index:: single: environment variables; setting
195 Set the environment variable named *varname* to the string *value*. Such
196 changes to the environment affect subprocesses started with :func:`os.system`,
197 :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
202 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
203 cause memory leaks. Refer to the system documentation for putenv.
205 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
206 automatically translated into corresponding calls to :func:`putenv`; however,
207 calls to :func:`putenv` don't update ``os.environ``, so it is actually
208 preferable to assign to items of ``os.environ``.
211 .. function:: setegid(egid)
213 Set the current process's effective group id. Availability: Unix.
216 .. function:: seteuid(euid)
218 Set the current process's effective user id. Availability: Unix.
221 .. function:: setgid(gid)
223 Set the current process' group id. Availability: Unix.
226 .. function:: setgroups(groups)
228 Set the list of supplemental group ids associated with the current process to
229 *groups*. *groups* must be a sequence, and each element must be an integer
230 identifying a group. This operation is typically available only to the superuser.
233 .. versionadded:: 2.2
236 .. function:: setpgrp()
238 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
239 which version is implemented (if any). See the Unix manual for the semantics.
243 .. function:: setpgid(pid, pgrp)
245 Call the system call :cfunc:`setpgid` to set the process group id of the
246 process with id *pid* to the process group with id *pgrp*. See the Unix manual
247 for the semantics. Availability: Unix.
250 .. function:: setreuid(ruid, euid)
252 Set the current process's real and effective user ids. Availability: Unix.
255 .. function:: setregid(rgid, egid)
257 Set the current process's real and effective group ids. Availability: Unix.
260 .. function:: getsid(pid)
262 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
265 .. versionadded:: 2.4
268 .. function:: setsid()
270 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
274 .. function:: setuid(uid)
276 .. index:: single: user; id, setting
278 Set the current process's user id. Availability: Unix.
281 .. placed in this section since it relates to errno.... a little weak
282 .. function:: strerror(code)
284 Return the error message corresponding to the error code in *code*.
285 On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
286 error number, :exc:`ValueError` is raised. Availability: Unix, Windows.
289 .. function:: umask(mask)
291 Set the current numeric umask and return the previous umask. Availability:
295 .. function:: uname()
298 single: gethostname() (in module socket)
299 single: gethostbyaddr() (in module socket)
301 Return a 5-tuple containing information identifying the current operating
302 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
303 machine)``. Some systems truncate the nodename to 8 characters or to the
304 leading component; a better way to get the hostname is
305 :func:`socket.gethostname` or even
306 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
310 .. function:: unsetenv(varname)
312 .. index:: single: environment variables; deleting
314 Unset (delete) the environment variable named *varname*. Such changes to the
315 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
316 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
318 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
319 automatically translated into a corresponding call to :func:`unsetenv`; however,
320 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
321 preferable to delete items of ``os.environ``.
329 These functions create new file objects. (See also :func:`open`.)
332 .. function:: fdopen(fd[, mode[, bufsize]])
334 .. index:: single: I/O control; buffering
336 Return an open file object connected to the file descriptor *fd*. The *mode*
337 and *bufsize* arguments have the same meaning as the corresponding arguments to
338 the built-in :func:`open` function. Availability: Unix, Windows.
340 .. versionchanged:: 2.3
341 When specified, the *mode* argument must now start with one of the letters
342 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
344 .. versionchanged:: 2.5
345 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
346 set on the file descriptor (which the :cfunc:`fdopen` implementation already
347 does on most platforms).
350 .. function:: popen(command[, mode[, bufsize]])
352 Open a pipe to or from *command*. The return value is an open file object
353 connected to the pipe, which can be read or written depending on whether *mode*
354 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
355 the corresponding argument to the built-in :func:`open` function. The exit
356 status of the command (encoded in the format specified for :func:`wait`) is
357 available as the return value of the :meth:`~file.close` method of the file object,
358 except that when the exit status is zero (termination without errors), ``None``
359 is returned. Availability: Unix, Windows.
362 This function is obsolete. Use the :mod:`subprocess` module. Check
363 especially the :ref:`subprocess-replacements` section.
365 .. versionchanged:: 2.0
366 This function worked unreliably under Windows in earlier versions of Python.
367 This was due to the use of the :cfunc:`_popen` function from the libraries
368 provided with Windows. Newer versions of Python do not use the broken
369 implementation from the Windows libraries.
372 .. function:: tmpfile()
374 Return a new file object opened in update mode (``w+b``). The file has no
375 directory entries associated with it and will be automatically deleted once
376 there are no file descriptors for the file. Availability: Unix,
379 There are a number of different :func:`popen\*` functions that provide slightly
380 different ways to create subprocesses.
383 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
386 For each of the :func:`popen\*` variants, if *bufsize* is specified, it
387 specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
388 string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
389 file objects should be opened in binary or text mode. The default value for
392 Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
393 case arguments will be passed directly to the program without shell intervention
394 (as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
395 (as with :func:`os.system`).
397 These methods do not make it possible to retrieve the exit status from the child
398 processes. The only way to control the input and output streams and also
399 retrieve the return codes is to use the :mod:`subprocess` module; these are only
402 For a discussion of possible deadlock conditions related to the use of these
403 functions, see :ref:`popen2-flow-control`.
406 .. function:: popen2(cmd[, mode[, bufsize]])
408 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
412 This function is obsolete. Use the :mod:`subprocess` module. Check
413 especially the :ref:`subprocess-replacements` section.
415 Availability: Unix, Windows.
417 .. versionadded:: 2.0
420 .. function:: popen3(cmd[, mode[, bufsize]])
422 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
423 child_stdout, child_stderr)``.
426 This function is obsolete. Use the :mod:`subprocess` module. Check
427 especially the :ref:`subprocess-replacements` section.
429 Availability: Unix, Windows.
431 .. versionadded:: 2.0
434 .. function:: popen4(cmd[, mode[, bufsize]])
436 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
437 child_stdout_and_stderr)``.
440 This function is obsolete. Use the :mod:`subprocess` module. Check
441 especially the :ref:`subprocess-replacements` section.
443 Availability: Unix, Windows.
445 .. versionadded:: 2.0
447 (Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
448 point of view of the child process, so *child_stdin* is the child's standard
451 This functionality is also available in the :mod:`popen2` module using functions
452 of the same names, but the return values of those functions have a different
458 File Descriptor Operations
459 --------------------------
461 These functions operate on I/O streams referenced using file descriptors.
463 File descriptors are small integers corresponding to a file that has been opened
464 by the current process. For example, standard input is usually file descriptor
465 0, standard output is 1, and standard error is 2. Further files opened by a
466 process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
467 is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
471 .. function:: close(fd)
473 Close file descriptor *fd*. Availability: Unix, Windows.
477 This function is intended for low-level I/O and must be applied to a file
478 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
479 object" returned by the built-in function :func:`open` or by :func:`popen` or
480 :func:`fdopen`, use its :meth:`~file.close` method.
483 .. function:: closerange(fd_low, fd_high)
485 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
486 ignoring errors. Availability: Unix, Windows. Equivalent to::
488 for fd in xrange(fd_low, fd_high):
494 .. versionadded:: 2.6
497 .. function:: dup(fd)
499 Return a duplicate of file descriptor *fd*. Availability: Unix,
503 .. function:: dup2(fd, fd2)
505 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
506 Availability: Unix, Windows.
509 .. function:: fchmod(fd, mode)
511 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
512 for :func:`chmod` for possible values of *mode*. Availability: Unix.
514 .. versionadded:: 2.6
517 .. function:: fchown(fd, uid, gid)
519 Change the owner and group id of the file given by *fd* to the numeric *uid*
520 and *gid*. To leave one of the ids unchanged, set it to -1.
523 .. versionadded:: 2.6
526 .. function:: fdatasync(fd)
528 Force write of file with filedescriptor *fd* to disk. Does not force update of
529 metadata. Availability: Unix.
532 This function is not available on MacOS.
535 .. function:: fpathconf(fd, name)
537 Return system configuration information relevant to an open file. *name*
538 specifies the configuration value to retrieve; it may be a string which is the
539 name of a defined system value; these names are specified in a number of
540 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
541 additional names as well. The names known to the host operating system are
542 given in the ``pathconf_names`` dictionary. For configuration variables not
543 included in that mapping, passing an integer for *name* is also accepted.
546 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
547 specific value for *name* is not supported by the host system, even if it is
548 included in ``pathconf_names``, an :exc:`OSError` is raised with
549 :const:`errno.EINVAL` for the error number.
552 .. function:: fstat(fd)
554 Return status for file descriptor *fd*, like :func:`stat`. Availability:
558 .. function:: fstatvfs(fd)
560 Return information about the filesystem containing the file associated with file
561 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
564 .. function:: fsync(fd)
566 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
567 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
569 If you're starting with a Python file object *f*, first do ``f.flush()``, and
570 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
571 with *f* are written to disk. Availability: Unix, and Windows
575 .. function:: ftruncate(fd, length)
577 Truncate the file corresponding to file descriptor *fd*, so that it is at most
578 *length* bytes in size. Availability: Unix.
581 .. function:: isatty(fd)
583 Return ``True`` if the file descriptor *fd* is open and connected to a
584 tty(-like) device, else ``False``. Availability: Unix.
587 .. function:: lseek(fd, pos, how)
589 Set the current position of file descriptor *fd* to position *pos*, modified
590 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
591 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
592 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
593 the file. Availability: Unix, Windows.
596 .. function:: open(file, flags[, mode])
598 Open the file *file* and set various flags according to *flags* and possibly its
599 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
600 current umask value is first masked out. Return the file descriptor for the
601 newly opened file. Availability: Unix, Windows.
603 For a description of the flag and mode values, see the C run-time documentation;
604 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
605 this module too (see below).
609 This function is intended for low-level I/O. For normal usage, use the
610 built-in function :func:`open`, which returns a "file object" with
611 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
612 wrap a file descriptor in a "file object", use :func:`fdopen`.
615 .. function:: openpty()
617 .. index:: module: pty
619 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
620 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
621 approach, use the :mod:`pty` module. Availability: some flavors of
627 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
628 and writing, respectively. Availability: Unix, Windows.
631 .. function:: read(fd, n)
633 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
634 bytes read. If the end of the file referred to by *fd* has been reached, an
635 empty string is returned. Availability: Unix, Windows.
639 This function is intended for low-level I/O and must be applied to a file
640 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a "file object"
641 returned by the built-in function :func:`open` or by :func:`popen` or
642 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
643 :meth:`~file.readline` methods.
646 .. function:: tcgetpgrp(fd)
648 Return the process group associated with the terminal given by *fd* (an open
649 file descriptor as returned by :func:`os.open`). Availability: Unix.
652 .. function:: tcsetpgrp(fd, pg)
654 Set the process group associated with the terminal given by *fd* (an open file
655 descriptor as returned by :func:`os.open`) to *pg*. Availability: Unix.
658 .. function:: ttyname(fd)
660 Return a string which specifies the terminal device associated with
661 file descriptor *fd*. If *fd* is not associated with a terminal device, an
662 exception is raised. Availability: Unix.
665 .. function:: write(fd, str)
667 Write the string *str* to file descriptor *fd*. Return the number of bytes
668 actually written. Availability: Unix, Windows.
672 This function is intended for low-level I/O and must be applied to a file
673 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
674 object" returned by the built-in function :func:`open` or by :func:`popen` or
675 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
676 :meth:`~file.write` method.
678 The following constants are options for the *flags* parameter to the
679 :func:`~os.open` function. They can be combined using the bitwise OR operator
680 ``|``. Some of them are not available on all platforms. For descriptions of
681 their availability and use, consult the :manpage:`open(2)` manual page on Unix
682 or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
693 These constants are available on Unix and Windows.
705 These constants are only available on Unix.
716 These constants are only available on Windows.
725 These constants are GNU extensions and not present if they are not defined by
733 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
734 respectively. Availability: Windows, Unix.
736 .. versionadded:: 2.5
741 Files and Directories
742 ---------------------
744 .. function:: access(path, mode)
746 Use the real uid/gid to test for access to *path*. Note that most operations
747 will use the effective uid/gid, therefore this routine can be used in a
748 suid/sgid environment to test if the invoking user has the specified access to
749 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
750 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
751 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
752 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
753 information. Availability: Unix, Windows.
757 Using :func:`access` to check if a user is authorized to e.g. open a file
758 before actually doing so using :func:`open` creates a security hole,
759 because the user might exploit the short time interval between checking
760 and opening the file to manipulate it.
764 I/O operations may fail even when :func:`access` indicates that they would
765 succeed, particularly for operations on network filesystems which may have
766 permissions semantics beyond the usual POSIX permission-bit model.
771 Value to pass as the *mode* parameter of :func:`access` to test the existence of
777 Value to include in the *mode* parameter of :func:`access` to test the
778 readability of *path*.
783 Value to include in the *mode* parameter of :func:`access` to test the
784 writability of *path*.
789 Value to include in the *mode* parameter of :func:`access` to determine if
790 *path* can be executed.
793 .. function:: chdir(path)
795 .. index:: single: directory; changing
797 Change the current working directory to *path*. Availability: Unix,
801 .. function:: fchdir(fd)
803 Change the current working directory to the directory represented by the file
804 descriptor *fd*. The descriptor must refer to an opened directory, not an open
805 file. Availability: Unix.
807 .. versionadded:: 2.3
810 .. function:: getcwd()
812 Return a string representing the current working directory. Availability:
816 .. function:: getcwdu()
818 Return a Unicode object representing the current working directory.
819 Availability: Unix, Windows.
821 .. versionadded:: 2.3
824 .. function:: chflags(path, flags)
826 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
827 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
842 .. versionadded:: 2.6
845 .. function:: chroot(path)
847 Change the root directory of the current process to *path*. Availability:
850 .. versionadded:: 2.2
853 .. function:: chmod(path, mode)
855 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
856 following values (as defined in the :mod:`stat` module) or bitwise ORed
857 combinations of them:
860 * :data:`stat.S_ISUID`
861 * :data:`stat.S_ISGID`
862 * :data:`stat.S_ENFMT`
863 * :data:`stat.S_ISVTX`
864 * :data:`stat.S_IREAD`
865 * :data:`stat.S_IWRITE`
866 * :data:`stat.S_IEXEC`
867 * :data:`stat.S_IRWXU`
868 * :data:`stat.S_IRUSR`
869 * :data:`stat.S_IWUSR`
870 * :data:`stat.S_IXUSR`
871 * :data:`stat.S_IRWXG`
872 * :data:`stat.S_IRGRP`
873 * :data:`stat.S_IWGRP`
874 * :data:`stat.S_IXGRP`
875 * :data:`stat.S_IRWXO`
876 * :data:`stat.S_IROTH`
877 * :data:`stat.S_IWOTH`
878 * :data:`stat.S_IXOTH`
880 Availability: Unix, Windows.
884 Although Windows supports :func:`chmod`, you can only set the file's read-only
885 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
886 constants or a corresponding integer value). All other bits are
890 .. function:: chown(path, uid, gid)
892 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
893 one of the ids unchanged, set it to -1. Availability: Unix.
896 .. function:: lchflags(path, flags)
898 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
899 follow symbolic links. Availability: Unix.
901 .. versionadded:: 2.6
904 .. function:: lchmod(path, mode)
906 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
907 affects the symlink rather than the target. See the docs for :func:`chmod`
908 for possible values of *mode*. Availability: Unix.
910 .. versionadded:: 2.6
913 .. function:: lchown(path, uid, gid)
915 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
916 function will not follow symbolic links. Availability: Unix.
918 .. versionadded:: 2.3
921 .. function:: link(source, link_name)
923 Create a hard link pointing to *source* named *link_name*. Availability:
927 .. function:: listdir(path)
929 Return a list containing the names of the entries in the directory given by
930 *path*. The list is in arbitrary order. It does not include the special
931 entries ``'.'`` and ``'..'`` even if they are present in the
932 directory. Availability: Unix, Windows.
934 .. versionchanged:: 2.3
935 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
936 a list of Unicode objects. Undecodable filenames will still be returned as
940 .. function:: lstat(path)
942 Like :func:`stat`, but do not follow symbolic links. This is an alias for
943 :func:`stat` on platforms that do not support symbolic links, such as
947 .. function:: mkfifo(path[, mode])
949 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
950 *mode* is ``0666`` (octal). The current umask value is first masked out from
951 the mode. Availability: Unix.
953 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
954 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
955 rendezvous between "client" and "server" type processes: the server opens the
956 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
957 doesn't open the FIFO --- it just creates the rendezvous point.
960 .. function:: mknod(filename[, mode=0600, device])
962 Create a filesystem node (file, device special file or named pipe) named
963 *filename*. *mode* specifies both the permissions to use and the type of node to
964 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
965 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
966 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
967 For ``stat.S_IFCHR`` and
968 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
969 :func:`os.makedev`), otherwise it is ignored.
971 .. versionadded:: 2.3
974 .. function:: major(device)
976 Extract the device major number from a raw device number (usually the
977 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
979 .. versionadded:: 2.3
982 .. function:: minor(device)
984 Extract the device minor number from a raw device number (usually the
985 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
987 .. versionadded:: 2.3
990 .. function:: makedev(major, minor)
992 Compose a raw device number from the major and minor device numbers.
994 .. versionadded:: 2.3
997 .. function:: mkdir(path[, mode])
999 Create a directory named *path* with numeric mode *mode*. The default *mode* is
1000 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
1001 current umask value is first masked out. Availability: Unix, Windows.
1003 It is also possible to create temporary directories; see the
1004 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1007 .. function:: makedirs(path[, mode])
1010 single: directory; creating
1011 single: UNC paths; and os.makedirs()
1013 Recursive directory creation function. Like :func:`mkdir`, but makes all
1014 intermediate-level directories needed to contain the leaf directory. Throws an
1015 :exc:`error` exception if the leaf directory already exists or cannot be
1016 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
1017 ignored. Where it is used, the current umask value is first masked out.
1021 :func:`makedirs` will become confused if the path elements to create include
1024 .. versionadded:: 1.5.2
1026 .. versionchanged:: 2.3
1027 This function now handles UNC paths correctly.
1030 .. function:: pathconf(path, name)
1032 Return system configuration information relevant to a named file. *name*
1033 specifies the configuration value to retrieve; it may be a string which is the
1034 name of a defined system value; these names are specified in a number of
1035 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1036 additional names as well. The names known to the host operating system are
1037 given in the ``pathconf_names`` dictionary. For configuration variables not
1038 included in that mapping, passing an integer for *name* is also accepted.
1041 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1042 specific value for *name* is not supported by the host system, even if it is
1043 included in ``pathconf_names``, an :exc:`OSError` is raised with
1044 :const:`errno.EINVAL` for the error number.
1047 .. data:: pathconf_names
1049 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1050 the integer values defined for those names by the host operating system. This
1051 can be used to determine the set of names known to the system. Availability:
1055 .. function:: readlink(path)
1057 Return a string representing the path to which the symbolic link points. The
1058 result may be either an absolute or relative pathname; if it is relative, it may
1059 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1062 .. versionchanged:: 2.6
1063 If the *path* is a Unicode object the result will also be a Unicode object.
1068 .. function:: remove(path)
1070 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
1071 raised; see :func:`rmdir` below to remove a directory. This is identical to
1072 the :func:`unlink` function documented below. On Windows, attempting to
1073 remove a file that is in use causes an exception to be raised; on Unix, the
1074 directory entry is removed but the storage allocated to the file is not made
1075 available until the original file is no longer in use. Availability: Unix,
1079 .. function:: removedirs(path)
1081 .. index:: single: directory; deleting
1083 Remove directories recursively. Works like :func:`rmdir` except that, if the
1084 leaf directory is successfully removed, :func:`removedirs` tries to
1085 successively remove every parent directory mentioned in *path* until an error
1086 is raised (which is ignored, because it generally means that a parent directory
1087 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1088 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1089 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1090 successfully removed.
1092 .. versionadded:: 1.5.2
1095 .. function:: rename(src, dst)
1097 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1098 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
1099 be replaced silently if the user has permission. The operation may fail on some
1100 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1101 the renaming will be an atomic operation (this is a POSIX requirement). On
1102 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1103 file; there may be no way to implement an atomic rename when *dst* names an
1104 existing file. Availability: Unix, Windows.
1107 .. function:: renames(old, new)
1109 Recursive directory or file renaming function. Works like :func:`rename`, except
1110 creation of any intermediate directories needed to make the new pathname good is
1111 attempted first. After the rename, directories corresponding to rightmost path
1112 segments of the old name will be pruned away using :func:`removedirs`.
1114 .. versionadded:: 1.5.2
1118 This function can fail with the new directory structure made if you lack
1119 permissions needed to remove the leaf directory or file.
1122 .. function:: rmdir(path)
1124 Remove (delete) the directory *path*. Only works when the directory is
1125 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
1126 directory trees, :func:`shutil.rmtree` can be used. Availability: Unix,
1130 .. function:: stat(path)
1132 Perform a :cfunc:`stat` system call on the given path. The return value is an
1133 object whose attributes correspond to the members of the :ctype:`stat`
1134 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1135 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
1136 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
1137 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1138 access), :attr:`st_mtime` (time of most recent content modification),
1139 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1140 Unix, or the time of creation on Windows)::
1143 >>> statinfo = os.stat('somefile.txt')
1145 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1146 >>> statinfo.st_size
1150 .. versionchanged:: 2.3
1151 If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
1152 seconds. Fractions of a second may be reported if the system supports that. On
1153 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1156 On some Unix systems (such as Linux), the following attributes may also be
1157 available: :attr:`st_blocks` (number of blocks allocated for file),
1158 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1159 inode device). :attr:`st_flags` (user defined flags for file).
1161 On other Unix systems (such as FreeBSD), the following attributes may be
1162 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1163 (file generation number), :attr:`st_birthtime` (time of file creation).
1165 On Mac OS systems, the following attributes may also be available:
1166 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1168 On RISCOS systems, the following attributes are also available: :attr:`st_ftype`
1169 (file type), :attr:`st_attrs` (attributes), :attr:`st_obtype` (object type).
1171 .. index:: module: stat
1173 For backward compatibility, the return value of :func:`stat` is also accessible
1174 as a tuple of at least 10 integers giving the most important (and portable)
1175 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1176 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1177 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1178 :attr:`st_ctime`. More items may be added at the end by some implementations.
1179 The standard module :mod:`stat` defines functions and constants that are useful
1180 for extracting information from a :ctype:`stat` structure. (On Windows, some
1181 items are filled with dummy values.)
1185 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1186 :attr:`st_ctime` members depends on the operating system and the file system.
1187 For example, on Windows systems using the FAT or FAT32 file systems,
1188 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1189 resolution. See your operating system documentation for details.
1191 Availability: Unix, Windows.
1193 .. versionchanged:: 2.2
1194 Added access to values as attributes of the returned object.
1196 .. versionchanged:: 2.5
1197 Added :attr:`st_gen` and :attr:`st_birthtime`.
1200 .. function:: stat_float_times([newvalue])
1202 Determine whether :class:`stat_result` represents time stamps as float objects.
1203 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1204 ``False``, future calls return ints. If *newvalue* is omitted, return the
1207 For compatibility with older Python versions, accessing :class:`stat_result` as
1208 a tuple always returns integers.
1210 .. versionchanged:: 2.5
1211 Python now returns float values by default. Applications which do not work
1212 correctly with floating point time stamps can use this function to restore the
1215 The resolution of the timestamps (that is the smallest possible fraction)
1216 depends on the system. Some systems only support second resolution; on these
1217 systems, the fraction will always be zero.
1219 It is recommended that this setting is only changed at program startup time in
1220 the *__main__* module; libraries should never change this setting. If an
1221 application uses a library that works incorrectly if floating point time stamps
1222 are processed, this application should turn the feature off until the library
1226 .. function:: statvfs(path)
1228 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1229 an object whose attributes describe the filesystem on the given path, and
1230 correspond to the members of the :ctype:`statvfs` structure, namely:
1231 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1232 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1233 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1235 .. index:: module: statvfs
1237 For backward compatibility, the return value is also accessible as a tuple whose
1238 values correspond to the attributes, in the order given above. The standard
1239 module :mod:`statvfs` defines constants that are useful for extracting
1240 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1241 this remains useful when writing code that needs to work with versions of Python
1242 that don't support accessing the fields as attributes.
1244 .. versionchanged:: 2.2
1245 Added access to values as attributes of the returned object.
1248 .. function:: symlink(source, link_name)
1250 Create a symbolic link pointing to *source* named *link_name*. Availability:
1254 .. function:: tempnam([dir[, prefix]])
1256 Return a unique path name that is reasonable for creating a temporary file.
1257 This will be an absolute path that names a potential directory entry in the
1258 directory *dir* or a common location for temporary files if *dir* is omitted or
1259 ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
1260 to the filename. Applications are responsible for properly creating and
1261 managing files created using paths returned by :func:`tempnam`; no automatic
1262 cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
1263 overrides *dir*, while on Windows :envvar:`TMP` is used. The specific
1264 behavior of this function depends on the C library implementation; some aspects
1265 are underspecified in system documentation.
1269 Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1270 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1272 Availability: Unix, Windows.
1275 .. function:: tmpnam()
1277 Return a unique path name that is reasonable for creating a temporary file.
1278 This will be an absolute path that names a potential directory entry in a common
1279 location for temporary files. Applications are responsible for properly
1280 creating and managing files created using paths returned by :func:`tmpnam`; no
1281 automatic cleanup is provided.
1285 Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1286 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1288 Availability: Unix, Windows. This function probably shouldn't be used on
1289 Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1290 name in the root directory of the current drive, and that's generally a poor
1291 location for a temp file (depending on privileges, you may not even be able to
1292 open a file using this name).
1297 The maximum number of unique names that :func:`tmpnam` will generate before
1301 .. function:: unlink(path)
1303 Remove (delete) the file *path*. This is the same function as
1304 :func:`remove`; the :func:`unlink` name is its traditional Unix
1305 name. Availability: Unix, Windows.
1308 .. function:: utime(path, times)
1310 Set the access and modified times of the file specified by *path*. If *times*
1311 is ``None``, then the file's access and modified times are set to the current
1312 time. (The effect is similar to running the Unix program :program:`touch` on
1313 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1314 ``(atime, mtime)`` which is used to set the access and modified times,
1315 respectively. Whether a directory can be given for *path* depends on whether
1316 the operating system implements directories as files (for example, Windows
1317 does not). Note that the exact times you set here may not be returned by a
1318 subsequent :func:`stat` call, depending on the resolution with which your
1319 operating system records access and modification times; see :func:`stat`.
1321 .. versionchanged:: 2.0
1322 Added support for ``None`` for *times*.
1324 Availability: Unix, Windows.
1327 .. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1330 single: directory; walking
1331 single: directory; traversal
1333 Generate the file names in a directory tree by walking the tree
1334 either top-down or bottom-up. For each directory in the tree rooted at directory
1335 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1338 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1339 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1340 *filenames* is a list of the names of the non-directory files in *dirpath*.
1341 Note that the names in the lists contain no path components. To get a full path
1342 (which begins with *top*) to a file or directory in *dirpath*, do
1343 ``os.path.join(dirpath, name)``.
1345 If optional argument *topdown* is ``True`` or not specified, the triple for a
1346 directory is generated before the triples for any of its subdirectories
1347 (directories are generated top-down). If *topdown* is ``False``, the triple for a
1348 directory is generated after the triples for all of its subdirectories
1349 (directories are generated bottom-up).
1351 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
1352 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1353 recurse into the subdirectories whose names remain in *dirnames*; this can be
1354 used to prune the search, impose a specific order of visiting, or even to inform
1355 :func:`walk` about directories the caller creates or renames before it resumes
1356 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
1357 ineffective, because in bottom-up mode the directories in *dirnames* are
1358 generated before *dirpath* itself is generated.
1360 By default errors from the :func:`listdir` call are ignored. If optional
1361 argument *onerror* is specified, it should be a function; it will be called with
1362 one argument, an :exc:`OSError` instance. It can report the error to continue
1363 with the walk, or raise the exception to abort the walk. Note that the filename
1364 is available as the ``filename`` attribute of the exception object.
1366 By default, :func:`walk` will not walk down into symbolic links that resolve to
1367 directories. Set *followlinks* to ``True`` to visit directories pointed to by
1368 symlinks, on systems that support them.
1370 .. versionadded:: 2.6
1371 The *followlinks* parameter.
1375 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
1376 link points to a parent directory of itself. :func:`walk` does not keep track of
1377 the directories it visited already.
1381 If you pass a relative pathname, don't change the current working directory
1382 between resumptions of :func:`walk`. :func:`walk` never changes the current
1383 directory, and assumes that its caller doesn't either.
1385 This example displays the number of bytes taken by non-directory files in each
1386 directory under the starting directory, except that it doesn't look under any
1390 from os.path import join, getsize
1391 for root, dirs, files in os.walk('python/Lib/email'):
1392 print root, "consumes",
1393 print sum(getsize(join(root, name)) for name in files),
1394 print "bytes in", len(files), "non-directory files"
1396 dirs.remove('CVS') # don't visit CVS directories
1398 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
1399 doesn't allow deleting a directory before the directory is empty::
1401 # Delete everything reachable from the directory named in "top",
1402 # assuming there are no symbolic links.
1403 # CAUTION: This is dangerous! For example, if top == '/', it
1404 # could delete all your disk files.
1406 for root, dirs, files in os.walk(top, topdown=False):
1408 os.remove(os.path.join(root, name))
1410 os.rmdir(os.path.join(root, name))
1412 .. versionadded:: 2.3
1420 These functions may be used to create and manage processes.
1422 The various :func:`exec\*` functions take a list of arguments for the new
1423 program loaded into the process. In each case, the first of these arguments is
1424 passed to the new program as its own name rather than as an argument a user may
1425 have typed on a command line. For the C programmer, this is the ``argv[0]``
1426 passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1427 ['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1431 .. function:: abort()
1433 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1434 behavior is to produce a core dump; on Windows, the process immediately returns
1435 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1436 to register a handler for :const:`SIGABRT` will behave differently.
1437 Availability: Unix, Windows.
1440 .. function:: execl(path, arg0, arg1, ...)
1441 execle(path, arg0, arg1, ..., env)
1442 execlp(file, arg0, arg1, ...)
1443 execlpe(file, arg0, arg1, ..., env)
1445 execve(path, args, env)
1447 execvpe(file, args, env)
1449 These functions all execute a new program, replacing the current process; they
1450 do not return. On Unix, the new executable is loaded into the current process,
1451 and will have the same process id as the caller. Errors will be reported as
1452 :exc:`OSError` exceptions.
1454 The current process is replaced immediately. Open file objects and
1455 descriptors are not flushed, so if there may be data buffered
1456 on these open files, you should flush them using
1457 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
1458 :func:`exec\*` function.
1460 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1461 command-line arguments are passed. The "l" variants are perhaps the easiest
1462 to work with if the number of parameters is fixed when the code is written; the
1463 individual parameters simply become additional parameters to the :func:`execl\*`
1464 functions. The "v" variants are good when the number of parameters is
1465 variable, with the arguments being passed in a list or tuple as the *args*
1466 parameter. In either case, the arguments to the child process should start with
1467 the name of the command being run, but this is not enforced.
1469 The variants which include a "p" near the end (:func:`execlp`,
1470 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1471 :envvar:`PATH` environment variable to locate the program *file*. When the
1472 environment is being replaced (using one of the :func:`exec\*e` variants,
1473 discussed in the next paragraph), the new environment is used as the source of
1474 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1475 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1476 locate the executable; *path* must contain an appropriate absolute or relative
1479 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
1480 that these all end in "e"), the *env* parameter must be a mapping which is
1481 used to define the environment variables for the new process (these are used
1482 instead of the current process' environment); the functions :func:`execl`,
1483 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1484 inherit the environment of the current process.
1486 Availability: Unix, Windows.
1489 .. function:: _exit(n)
1491 Exit to the system with status *n*, without calling cleanup handlers, flushing
1492 stdio buffers, etc. Availability: Unix, Windows.
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`.
1499 The following exit codes are defined and can be used with :func:`_exit`,
1500 although they are not required. These are typically used for system programs
1501 written in Python, such as a mail server's external command delivery program.
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
1512 Exit code that means no error occurred. Availability: Unix.
1514 .. versionadded:: 2.3
1519 Exit code that means the command was used incorrectly, such as when the wrong
1520 number of arguments are given. Availability: Unix.
1522 .. versionadded:: 2.3
1525 .. data:: EX_DATAERR
1527 Exit code that means the input data was incorrect. Availability: Unix.
1529 .. versionadded:: 2.3
1532 .. data:: EX_NOINPUT
1534 Exit code that means an input file did not exist or was not readable.
1537 .. versionadded:: 2.3
1542 Exit code that means a specified user did not exist. Availability: Unix.
1544 .. versionadded:: 2.3
1549 Exit code that means a specified host did not exist. Availability: Unix.
1551 .. versionadded:: 2.3
1554 .. data:: EX_UNAVAILABLE
1556 Exit code that means that a required service is unavailable. Availability:
1559 .. versionadded:: 2.3
1562 .. data:: EX_SOFTWARE
1564 Exit code that means an internal software error was detected. Availability:
1567 .. versionadded:: 2.3
1572 Exit code that means an operating system error was detected, such as the
1573 inability to fork or create a pipe. Availability: Unix.
1575 .. versionadded:: 2.3
1580 Exit code that means some system file did not exist, could not be opened, or had
1581 some other kind of error. Availability: Unix.
1583 .. versionadded:: 2.3
1586 .. data:: EX_CANTCREAT
1588 Exit code that means a user specified output file could not be created.
1591 .. versionadded:: 2.3
1596 Exit code that means that an error occurred while doing I/O on some file.
1599 .. versionadded:: 2.3
1602 .. data:: EX_TEMPFAIL
1604 Exit code that means a temporary failure occurred. This indicates something
1605 that may not really be an error, such as a network connection that couldn't be
1606 made during a retryable operation. Availability: Unix.
1608 .. versionadded:: 2.3
1611 .. data:: EX_PROTOCOL
1613 Exit code that means that a protocol exchange was illegal, invalid, or not
1614 understood. Availability: Unix.
1616 .. versionadded:: 2.3
1621 Exit code that means that there were insufficient permissions to perform the
1622 operation (but not intended for file system problems). Availability: Unix.
1624 .. versionadded:: 2.3
1629 Exit code that means that some kind of configuration error occurred.
1632 .. versionadded:: 2.3
1635 .. data:: EX_NOTFOUND
1637 Exit code that means something like "an entry was not found". Availability:
1640 .. versionadded:: 2.3
1643 .. function:: fork()
1645 Fork a child process. Return ``0`` in the child and the child's process id in the
1646 parent. If an error occurs :exc:`OSError` is raised.
1648 Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
1649 known issues when using fork() from a thread.
1654 .. function:: forkpty()
1656 Fork a child process, using a new pseudo-terminal as the child's controlling
1657 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1658 new child's process id in the parent, and *fd* is the file descriptor of the
1659 master end of the pseudo-terminal. For a more portable approach, use the
1660 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
1661 Availability: some flavors of Unix.
1664 .. function:: kill(pid, sig)
1667 single: process; killing
1668 single: process; signalling
1670 Send signal *sig* to the process *pid*. Constants for the specific signals
1671 available on the host platform are defined in the :mod:`signal` module.
1675 .. function:: killpg(pgid, sig)
1678 single: process; killing
1679 single: process; signalling
1681 Send the signal *sig* to the process group *pgid*. Availability: Unix.
1683 .. versionadded:: 2.3
1686 .. function:: nice(increment)
1688 Add *increment* to the process's "niceness". Return the new niceness.
1692 .. function:: plock(op)
1694 Lock program segments into memory. The value of *op* (defined in
1695 ``<sys/lock.h>``) determines which segments are locked. Availability: Unix.
1698 .. function:: popen(...)
1704 Run child processes, returning opened pipes for communications. These functions
1705 are described in section :ref:`os-newstreams`.
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)
1717 Execute the program *path* in a new process.
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. Check especially the
1722 :ref:`subprocess-replacements` section.)
1724 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
1725 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1726 exits normally, or ``-signal``, where *signal* is the signal that killed the
1727 process. On Windows, the process id will actually be the process handle, so can
1728 be used with the :func:`waitpid` function.
1730 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1731 command-line arguments are passed. The "l" variants are perhaps the easiest
1732 to work with if the number of parameters is fixed when the code is written; the
1733 individual parameters simply become additional parameters to the
1734 :func:`spawnl\*` functions. The "v" variants are good when the number of
1735 parameters is variable, with the arguments being passed in a list or tuple as
1736 the *args* parameter. In either case, the arguments to the child process must
1737 start with the name of the command being run.
1739 The variants which include a second "p" near the end (:func:`spawnlp`,
1740 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1741 :envvar:`PATH` environment variable to locate the program *file*. When the
1742 environment is being replaced (using one of the :func:`spawn\*e` variants,
1743 discussed in the next paragraph), the new environment is used as the source of
1744 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1745 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1746 :envvar:`PATH` variable to locate the executable; *path* must contain an
1747 appropriate absolute or relative path.
1749 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
1750 (note that these all end in "e"), the *env* parameter must be a mapping
1751 which is used to define the environment variables for the new process (they are
1752 used instead of the current process' environment); the functions
1753 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1754 the new process to inherit the environment of the current process. Note that
1755 keys and values in the *env* dictionary must be strings; invalid keys or
1756 values will cause the function to fail, with a return value of ``127``.
1758 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1762 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1764 L = ['cp', 'index.html', '/dev/null']
1765 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1767 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1768 and :func:`spawnvpe` are not available on Windows.
1770 .. versionadded:: 1.6
1776 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1777 functions. If either of these values is given, the :func:`spawn\*` functions
1778 will return as soon as the new process has been created, with the process id as
1779 the return value. Availability: Unix, Windows.
1781 .. versionadded:: 1.6
1786 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1787 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1788 return until the new process has run to completion and will return the exit code
1789 of the process the run is successful, or ``-signal`` if a signal kills the
1790 process. Availability: Unix, Windows.
1792 .. versionadded:: 1.6
1798 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1799 functions. These are less portable than those listed above. :const:`P_DETACH`
1800 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1801 console of the calling process. If :const:`P_OVERLAY` is used, the current
1802 process will be replaced; the :func:`spawn\*` function will not return.
1803 Availability: Windows.
1805 .. versionadded:: 1.6
1808 .. function:: startfile(path[, operation])
1810 Start a file with its associated application.
1812 When *operation* is not specified or ``'open'``, this acts like double-clicking
1813 the file in Windows Explorer, or giving the file name as an argument to the
1814 :program:`start` command from the interactive command shell: the file is opened
1815 with whatever application (if any) its extension is associated.
1817 When another *operation* is given, it must be a "command verb" that specifies
1818 what should be done with the file. Common verbs documented by Microsoft are
1819 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1820 ``'find'`` (to be used on directories).
1822 :func:`startfile` returns as soon as the associated application is launched.
1823 There is no option to wait for the application to close, and no way to retrieve
1824 the application's exit status. The *path* parameter is relative to the current
1825 directory. If you want to use an absolute path, make sure the first character
1826 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1827 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1828 the path is properly encoded for Win32. Availability: Windows.
1830 .. versionadded:: 2.0
1832 .. versionadded:: 2.5
1833 The *operation* parameter.
1836 .. function:: system(command)
1838 Execute the command (a string) in a subshell. This is implemented by calling
1839 the Standard C function :cfunc:`system`, and has the same limitations.
1840 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the
1843 On Unix, the return value is the exit status of the process encoded in the
1844 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1845 of the return value of the C :cfunc:`system` function, so the return value of
1846 the Python function is system-dependent.
1848 On Windows, the return value is that returned by the system shell after running
1849 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1850 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1851 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1852 the command run; on systems using a non-native shell, consult your shell
1855 Availability: Unix, Windows.
1857 The :mod:`subprocess` module provides more powerful facilities for spawning new
1858 processes and retrieving their results; using that module is preferable to using
1859 this function. Use the :mod:`subprocess` module. Check especially the
1860 :ref:`subprocess-replacements` section.
1863 .. function:: times()
1865 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1866 other) times, in seconds. The items are: user time, system time, children's
1867 user time, children's system time, and elapsed real time since a fixed point in
1868 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
1869 corresponding Windows Platform API documentation. Availability: Unix,
1870 Windows. On Windows, only the first two items are filled, the others are zero.
1873 .. function:: wait()
1875 Wait for completion of a child process, and return a tuple containing its pid
1876 and exit status indication: a 16-bit number, whose low byte is the signal number
1877 that killed the process, and whose high byte is the exit status (if the signal
1878 number is zero); the high bit of the low byte is set if a core file was
1879 produced. Availability: Unix.
1882 .. function:: waitpid(pid, options)
1884 The details of this function differ on Unix and Windows.
1886 On Unix: Wait for completion of a child process given by process id *pid*, and
1887 return a tuple containing its process id and exit status indication (encoded as
1888 for :func:`wait`). The semantics of the call are affected by the value of the
1889 integer *options*, which should be ``0`` for normal operation.
1891 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1892 that specific process. If *pid* is ``0``, the request is for the status of any
1893 child in the process group of the current process. If *pid* is ``-1``, the
1894 request pertains to any child of the current process. If *pid* is less than
1895 ``-1``, status is requested for any process in the process group ``-pid`` (the
1896 absolute value of *pid*).
1898 An :exc:`OSError` is raised with the value of errno when the syscall
1901 On Windows: Wait for completion of a process given by process handle *pid*, and
1902 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1903 (shifting makes cross-platform use of the function easier). A *pid* less than or
1904 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1905 value of integer *options* has no effect. *pid* can refer to any process whose
1906 id is known, not necessarily a child process. The :func:`spawn` functions called
1907 with :const:`P_NOWAIT` return suitable process handles.
1910 .. function:: wait3([options])
1912 Similar to :func:`waitpid`, except no process id argument is given and a
1913 3-element tuple containing the child's process id, exit status indication, and
1914 resource usage information is returned. Refer to :mod:`resource`.\
1915 :func:`getrusage` for details on resource usage information. The option
1916 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1919 .. versionadded:: 2.5
1922 .. function:: wait4(pid, options)
1924 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1925 process id, exit status indication, and resource usage information is returned.
1926 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1927 information. The arguments to :func:`wait4` are the same as those provided to
1928 :func:`waitpid`. Availability: Unix.
1930 .. versionadded:: 2.5
1935 The option for :func:`waitpid` to return immediately if no child process status
1936 is available immediately. The function returns ``(0, 0)`` in this case.
1940 .. data:: WCONTINUED
1942 This option causes child processes to be reported if they have been continued
1943 from a job control stop since their status was last reported. Availability: Some
1946 .. versionadded:: 2.3
1951 This option causes child processes to be reported if they have been stopped but
1952 their current state has not been reported since they were stopped. Availability:
1955 .. versionadded:: 2.3
1957 The following functions take a process status code as returned by
1958 :func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1959 used to determine the disposition of a process.
1962 .. function:: WCOREDUMP(status)
1964 Return ``True`` if a core dump was generated for the process, otherwise
1965 return ``False``. Availability: Unix.
1967 .. versionadded:: 2.3
1970 .. function:: WIFCONTINUED(status)
1972 Return ``True`` if the process has been continued from a job control stop,
1973 otherwise return ``False``. Availability: Unix.
1975 .. versionadded:: 2.3
1978 .. function:: WIFSTOPPED(status)
1980 Return ``True`` if the process has been stopped, otherwise return
1981 ``False``. Availability: Unix.
1984 .. function:: WIFSIGNALED(status)
1986 Return ``True`` if the process exited due to a signal, otherwise return
1987 ``False``. Availability: Unix.
1990 .. function:: WIFEXITED(status)
1992 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
1993 otherwise return ``False``. Availability: Unix.
1996 .. function:: WEXITSTATUS(status)
1998 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1999 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
2003 .. function:: WSTOPSIG(status)
2005 Return the signal which caused the process to stop. Availability: Unix.
2008 .. function:: WTERMSIG(status)
2010 Return the signal which caused the process to exit. Availability: Unix.
2015 Miscellaneous System Information
2016 --------------------------------
2019 .. function:: confstr(name)
2021 Return string-valued system configuration values. *name* specifies the
2022 configuration value to retrieve; it may be a string which is the name of a
2023 defined system value; these names are specified in a number of standards (POSIX,
2024 Unix 95, Unix 98, and others). Some platforms define additional names as well.
2025 The names known to the host operating system are given as the keys of the
2026 ``confstr_names`` dictionary. For configuration variables not included in that
2027 mapping, passing an integer for *name* is also accepted. Availability:
2030 If the configuration value specified by *name* isn't defined, ``None`` is
2033 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2034 specific value for *name* is not supported by the host system, even if it is
2035 included in ``confstr_names``, an :exc:`OSError` is raised with
2036 :const:`errno.EINVAL` for the error number.
2039 .. data:: confstr_names
2041 Dictionary mapping names accepted by :func:`confstr` to the integer values
2042 defined for those names by the host operating system. This can be used to
2043 determine the set of names known to the system. Availability: Unix.
2046 .. function:: getloadavg()
2048 Return the number of processes in the system run queue averaged over the last
2049 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
2050 unobtainable. Availability: Unix.
2052 .. versionadded:: 2.3
2055 .. function:: sysconf(name)
2057 Return integer-valued system configuration values. If the configuration value
2058 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2059 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2060 provides information on the known names is given by ``sysconf_names``.
2064 .. data:: sysconf_names
2066 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2067 defined for those names by the host operating system. This can be used to
2068 determine the set of names known to the system. Availability: Unix.
2070 The following data values are used to support path manipulation operations. These
2071 are defined for all platforms.
2073 Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2078 The constant string used by the operating system to refer to the current
2079 directory. This is ``'.'`` for Windows and POSIX. Also available via
2085 The constant string used by the operating system to refer to the parent
2086 directory. This is ``'..'`` for Windows and POSIX. Also available via
2092 The character used by the operating system to separate pathname components.
2093 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
2094 is not sufficient to be able to parse or concatenate pathnames --- use
2095 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2096 useful. Also available via :mod:`os.path`.
2101 An alternative character used by the operating system to separate pathname
2102 components, or ``None`` if only one separator character exists. This is set to
2103 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2109 The character which separates the base filename from the extension; for example,
2110 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2112 .. versionadded:: 2.2
2117 The character conventionally used by the operating system to separate search
2118 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2119 Windows. Also available via :mod:`os.path`.
2124 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
2125 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
2130 The string used to separate (or, rather, terminate) lines on the current
2131 platform. This may be a single character, such as ``'\n'`` for POSIX, or
2132 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
2133 *os.linesep* as a line terminator when writing files opened in text mode (the
2134 default); use a single ``'\n'`` instead, on all platforms.
2139 The file path of the null device. For example: ``'/dev/null'`` for POSIX.
2140 Also available via :mod:`os.path`.
2142 .. versionadded:: 2.4
2147 Miscellaneous Functions
2148 -----------------------
2151 .. function:: urandom(n)
2153 Return a string of *n* random bytes suitable for cryptographic use.
2155 This function returns random bytes from an OS-specific randomness source. The
2156 returned data should be unpredictable enough for cryptographic applications,
2157 though its exact quality depends on the OS implementation. On a UNIX-like
2158 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
2159 If a randomness source is not found, :exc:`NotImplementedError` will be raised.
2161 .. versionadded:: 2.4