n | |
| :mod:`os` --- Miscellaneous operating system interfaces |
| ======================================================= |
| |
| .. module:: os |
| :synopsis: Miscellaneous operating system interfaces. |
| |
| |
n | This module provides a more portable way of using operating system dependent |
n | This module provides a portable way of using operating system dependent |
| functionality than importing a operating system dependent built-in module like |
| functionality. If you just want to read or write a file see :func:`open`, if |
| :mod:`posix` or :mod:`nt`. |
| you want to manipulate paths, see the :mod:`os.path` module, and if you want to |
| read all the lines in all the files on the command line see the :mod:`fileinput` |
| module. For creating temporary files and directories see the :mod:`tempfile` |
| module, and for high-level file and directory handling see the :mod:`shutil` |
| module. |
| |
n | This module searches for an operating system dependent built-in module like |
| :mod:`mac` or :mod:`posix` and exports the same functions and data as found |
| there. The design of all Python's built-in operating system dependent modules |
| The design of all built-in operating system dependent modules of Python is such |
| is such that as long as the same functionality is available, it uses the same |
| that as long as the same functionality is available, it uses the same interface; |
| interface; for example, the function ``os.stat(path)`` returns stat information |
| for example, the function ``os.stat(path)`` returns stat information about |
| about *path* in the same format (which happens to have originated with the POSIX |
| *path* in the same format (which happens to have originated with the POSIX |
| interface). |
| |
| Extensions peculiar to a particular operating system are also available through |
| the :mod:`os` module, but using them is of course a threat to portability! |
| |
n | Note that after the first time :mod:`os` is imported, there is *no* performance |
n | .. note:: |
| penalty in using functions from :mod:`os` instead of directly from the operating |
| system dependent built-in module, so there should be *no* reason not to use |
| :mod:`os`! |
| |
n | The :mod:`os` module contains many functions and data values. The items below |
n | If not separately noted, all functions that claim "Availability: Unix" are |
| and in the following sub-sections are all available directly from the :mod:`os` |
| supported on Mac OS X, which builds on a Unix core. |
| module. |
| |
n | .. % Frank Stajano <fstajano@uk.research.att.com> complained that it |
n | .. note:: |
| .. % wasn't clear that the entries described in the subsections were all |
| |
| .. % available at the module level (most uses of subsections are |
| All functions in this module raise :exc:`OSError` in the case of invalid or |
| .. % different); I think this is only a problem for the HTML version, |
| inaccessible file names and paths, or other arguments that have the correct |
| .. % where the relationship may not be as clear. |
| type, but are not accepted by the operating system. |
| .. % |
| |
| |
| .. exception:: error |
| |
n | .. index:: module: errno |
n | An alias for the built-in :exc:`OSError` exception. |
| |
| This exception is raised when a function returns a system-related error (not for |
| illegal argument types or other incidental errors). This is also known as the |
| built-in exception :exc:`OSError`. The accompanying value is a pair containing |
| the numeric error code from :cdata:`errno` and the corresponding string, as |
| would be printed by the C function :cfunc:`perror`. See the module |
| :mod:`errno`, which contains names for the error codes defined by the underlying |
| operating system. |
| |
| When exceptions are classes, this exception carries two attributes, |
| :attr:`errno` and :attr:`strerror`. The first holds the value of the C |
| :cdata:`errno` variable, and the latter holds the corresponding error message |
| from :cfunc:`strerror`. For exceptions that involve a file system path (such as |
| :func:`chdir` or :func:`unlink`), the exception instance will contain a third |
| attribute, :attr:`filename`, which is the file name passed to the function. |
| |
| |
| .. data:: name |
| |
| The name of the operating system dependent module imported. The following names |
| have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``, |
| ``'ce'``, ``'java'``, ``'riscos'``. |
n | |
| |
| .. data:: path |
| |
| The corresponding operating system dependent standard module for pathname |
| operations, such as :mod:`posixpath` or :mod:`macpath`. Thus, given the proper |
| imports, ``os.path.split(file)`` is equivalent to but more portable than |
| ``posixpath.split(file)``. Note that this is also an importable module: it may |
| be imported directly as :mod:`os.path`. |
| |
| |
| .. _os-procinfo: |
| |
| Process Parameters |
| ------------------ |
| |
| These functions and data items provide information and operate on the current |
| |
| Set the current process' group id. Availability: Unix. |
| |
| |
| .. function:: setgroups(groups) |
| |
| Set the list of supplemental group ids associated with the current process to |
| *groups*. *groups* must be a sequence, and each element must be an integer |
n | identifying a group. This operation is typical available only to the superuser. |
n | identifying a group. This operation is typically available only to the superuser. |
| Availability: Unix. |
| |
| .. versionadded:: 2.2 |
| |
| |
| .. function:: setpgrp() |
| |
n | Calls the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on |
n | Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on |
| which version is implemented (if any). See the Unix manual for the semantics. |
| Availability: Unix. |
| |
| |
| .. function:: setpgid(pid, pgrp) |
| |
n | Calls the system call :cfunc:`setpgid` to set the process group id of the |
n | Call the system call :cfunc:`setpgid` to set the process group id of the |
| process with id *pid* to the process group with id *pgrp*. See the Unix manual |
| for the semantics. Availability: Unix. |
| |
| |
| .. function:: setreuid(ruid, euid) |
| |
| Set the current process's real and effective user ids. Availability: Unix. |
| |
| |
| .. function:: setregid(rgid, egid) |
| |
| Set the current process's real and effective group ids. Availability: Unix. |
| |
| |
| .. function:: getsid(pid) |
| |
n | Calls the system call :cfunc:`getsid`. See the Unix manual for the semantics. |
n | Call the system call :cfunc:`getsid`. See the Unix manual for the semantics. |
| Availability: Unix. |
| |
| .. versionadded:: 2.4 |
| |
| |
| .. function:: setsid() |
| |
n | Calls the system call :cfunc:`setsid`. See the Unix manual for the semantics. |
n | Call the system call :cfunc:`setsid`. See the Unix manual for the semantics. |
| Availability: Unix. |
| |
| |
| .. function:: setuid(uid) |
| |
| .. index:: single: user; id, setting |
| |
n | Set the current process' user id. Availability: Unix. |
n | Set the current process's user id. Availability: Unix. |
| |
n | |
| .. % placed in this section since it relates to errno.... a little weak |
| .. placed in this section since it relates to errno.... a little weak |
| |
| |
| .. function:: strerror(code) |
| |
| Return the error message corresponding to the error code in *code*. |
n | Availability: Unix, Windows. |
n | On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown |
| error number, :exc:`ValueError` is raised. Availability: Unix, Windows. |
| |
| |
| .. function:: umask(mask) |
| |
n | Set the current numeric umask and returns the previous umask. Availability: |
n | Set the current numeric umask and return the previous umask. Availability: |
| Unix, Windows. |
| |
| |
| .. function:: uname() |
| |
| .. index:: |
| single: gethostname() (in module socket) |
| single: gethostbyaddr() (in module socket) |
| |
| Open a pipe to or from *command*. The return value is an open file object |
| connected to the pipe, which can be read or written depending on whether *mode* |
| is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as |
| the corresponding argument to the built-in :func:`open` function. The exit |
| status of the command (encoded in the format specified for :func:`wait`) is |
| available as the return value of the :meth:`close` method of the file object, |
| except that when the exit status is zero (termination without errors), ``None`` |
n | is returned. Availability: Macintosh, Unix, Windows. |
n | is returned. Availability: Unix, Windows. |
| |
| .. deprecated:: 2.6 |
| This function is obsolete. Use the :mod:`subprocess` module. Check |
| especially the :ref:`subprocess-replacements` section. |
| |
| .. versionchanged:: 2.0 |
| This function worked unreliably under Windows in earlier versions of Python. |
| This was due to the use of the :cfunc:`_popen` function from the libraries |
| provided with Windows. Newer versions of Python do not use the broken |
| implementation from the Windows libraries. |
| |
| |
| .. function:: tmpfile() |
| |
| Return a new file object opened in update mode (``w+b``). The file has no |
| directory entries associated with it and will be automatically deleted once |
n | there are no file descriptors for the file. Availability: Macintosh, Unix, |
n | there are no file descriptors for the file. Availability: Unix, |
| Windows. |
| |
n | There are a number of different :func:`popen\*` functions that provide slightly |
| different ways to create subprocesses. |
| |
| .. deprecated:: 2.6 |
| All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess` |
| module. |
| |
| For each of the following :func:`popen` variants, if *bufsize* is specified, it |
| For each of the :func:`popen\*` variants, if *bufsize* is specified, it |
| specifies the buffer size for the I/O pipes. *mode*, if provided, should be the |
| string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the |
| file objects should be opened in binary or text mode. The default value for |
| *mode* is ``'t'``. |
| |
| Also, for each of these variants, on Unix, *cmd* may be a sequence, in which |
| case arguments will be passed directly to the program without shell intervention |
| (as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell |
| (as with :func:`os.system`). |
| |
| These methods do not make it possible to retrieve the exit status from the child |
| processes. The only way to control the input and output streams and also |
n | retrieve the return codes is to use the :class:`Popen3` and :class:`Popen4` |
n | retrieve the return codes is to use the :mod:`subprocess` module; these are only |
| classes from the :mod:`popen2` module; these are only available on Unix. |
| available on Unix. |
| |
| For a discussion of possible deadlock conditions related to the use of these |
n | functions, see "Flow Control Issues (XXX reference: popen2-flow-control.html)" |
| (section :ref:`popen2-flow-control`). |
| functions, see :ref:`popen2-flow-control`. |
| |
| |
| .. function:: popen2(cmd[, mode[, bufsize]]) |
| |
n | Executes *cmd* as a sub-process. Returns the file objects ``(child_stdin, |
n | Execute *cmd* as a sub-process and return the file objects ``(child_stdin, |
| child_stdout)``. Availability: Macintosh, Unix, Windows. |
| child_stdout)``. |
| |
| .. deprecated:: 2.6 |
| This function is obsolete. Use the :mod:`subprocess` module. Check |
| especially the :ref:`subprocess-replacements` section. |
| |
| Availability: Unix, Windows. |
| |
| .. versionadded:: 2.0 |
| |
| |
| .. function:: popen3(cmd[, mode[, bufsize]]) |
| |
n | Executes *cmd* as a sub-process. Returns the file objects ``(child_stdin, |
n | Execute *cmd* as a sub-process and return the file objects ``(child_stdin, |
| child_stdout, child_stderr)``. Availability: Macintosh, Unix, Windows. |
| child_stdout, child_stderr)``. |
| |
| .. deprecated:: 2.6 |
| This function is obsolete. Use the :mod:`subprocess` module. Check |
| especially the :ref:`subprocess-replacements` section. |
| |
| Availability: Unix, Windows. |
| |
| .. versionadded:: 2.0 |
| |
| |
| .. function:: popen4(cmd[, mode[, bufsize]]) |
| |
n | Executes *cmd* as a sub-process. Returns the file objects ``(child_stdin, |
n | Execute *cmd* as a sub-process and return the file objects ``(child_stdin, |
| child_stdout_and_stderr)``. Availability: Macintosh, Unix, Windows. |
| child_stdout_and_stderr)``. |
| |
| .. deprecated:: 2.6 |
| This function is obsolete. Use the :mod:`subprocess` module. Check |
| especially the :ref:`subprocess-replacements` section. |
| |
| Availability: Unix, Windows. |
| |
| .. versionadded:: 2.0 |
| |
| (Note that ``child_stdin, child_stdout, and child_stderr`` are named from the |
| point of view of the child process, so *child_stdin* is the child's standard |
| input.) |
| |
| This functionality is also available in the :mod:`popen2` module using functions |
| 0, standard output is 1, and standard error is 2. Further files opened by a |
| process will then be assigned 3, 4, 5, and so forth. The name "file descriptor" |
| is slightly deceptive; on Unix platforms, sockets and pipes are also referenced |
| by file descriptors. |
| |
| |
| .. function:: close(fd) |
| |
n | Close file descriptor *fd*. Availability: Macintosh, Unix, Windows. |
n | Close file descriptor *fd*. Availability: Unix, Windows. |
| |
| .. note:: |
| |
| This function is intended for low-level I/O and must be applied to a file |
| descriptor as returned by :func:`open` or :func:`pipe`. To close a "file |
| object" returned by the built-in function :func:`open` or by :func:`popen` or |
| :func:`fdopen`, use its :meth:`close` method. |
| |
| |
n | .. function:: closerange(fd_low, fd_high) |
| |
| Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive), |
| ignoring errors. Availability: Unix, Windows. Equivalent to:: |
| |
| for fd in xrange(fd_low, fd_high): |
| try: |
| os.close(fd) |
| except OSError: |
| pass |
| |
| .. versionadded:: 2.6 |
| |
| |
| .. function:: dup(fd) |
| |
n | Return a duplicate of file descriptor *fd*. Availability: Macintosh, Unix, |
n | Return a duplicate of file descriptor *fd*. Availability: Unix, |
| Windows. |
| |
| |
| .. function:: dup2(fd, fd2) |
| |
| Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary. |
n | Availability: Macintosh, Unix, Windows. |
n | Availability: Unix, Windows. |
| |
| |
| .. function:: fchmod(fd, mode) |
| |
| Change the mode of the file given by *fd* to the numeric *mode*. See the docs |
| for :func:`chmod` for possible values of *mode*. Availability: Unix. |
| |
| .. versionadded:: 2.6 |
| |
| |
| .. function:: fchown(fd, uid, gid) |
| |
| Change the owner and group id of the file given by *fd* to the numeric *uid* |
| and *gid*. To leave one of the ids unchanged, set it to -1. |
| Availability: Unix. |
| |
| .. versionadded:: 2.6 |
| |
| |
| .. function:: fdatasync(fd) |
| |
| Force write of file with filedescriptor *fd* to disk. Does not force update of |
| metadata. Availability: Unix. |
| |
| |
| |
| Return system configuration information relevant to an open file. *name* |
| specifies the configuration value to retrieve; it may be a string which is the |
| name of a defined system value; these names are specified in a number of |
| standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define |
| additional names as well. The names known to the host operating system are |
| given in the ``pathconf_names`` dictionary. For configuration variables not |
| included in that mapping, passing an integer for *name* is also accepted. |
n | Availability: Macintosh, Unix. |
n | Availability: Unix. |
| |
| If *name* is a string and is not known, :exc:`ValueError` is raised. If a |
| specific value for *name* is not supported by the host system, even if it is |
| included in ``pathconf_names``, an :exc:`OSError` is raised with |
| :const:`errno.EINVAL` for the error number. |
| |
| |
| .. function:: fstat(fd) |
| |
| Return status for file descriptor *fd*, like :func:`stat`. Availability: |
n | Macintosh, Unix, Windows. |
n | Unix, Windows. |
| |
| |
| .. function:: fstatvfs(fd) |
| |
| Return information about the filesystem containing the file associated with file |
| descriptor *fd*, like :func:`statvfs`. Availability: Unix. |
| |
| |
| .. function:: fsync(fd) |
| |
| Force write of file with filedescriptor *fd* to disk. On Unix, this calls the |
| native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function. |
| |
| If you're starting with a Python file object *f*, first do ``f.flush()``, and |
| then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated |
n | with *f* are written to disk. Availability: Macintosh, Unix, and Windows |
n | with *f* are written to disk. Availability: Unix, and Windows |
| starting in 2.2.3. |
| |
| |
| .. function:: ftruncate(fd, length) |
| |
| Truncate the file corresponding to file descriptor *fd*, so that it is at most |
n | *length* bytes in size. Availability: Macintosh, Unix. |
n | *length* bytes in size. Availability: Unix. |
| |
| |
| .. function:: isatty(fd) |
| |
| Return ``True`` if the file descriptor *fd* is open and connected to a |
n | tty(-like) device, else ``False``. Availability: Macintosh, Unix. |
n | tty(-like) device, else ``False``. Availability: Unix. |
| |
| |
| .. function:: lseek(fd, pos, how) |
| |
n | Set the current position of file descriptor *fd* to position *pos*, modified by |
n | Set the current position of file descriptor *fd* to position *pos*, modified |
| *how*: ``0`` to set the position relative to the beginning of the file; ``1`` to |
| by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the |
| set it relative to the current position; ``2`` to set it relative to the end of |
| beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the |
| current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of |
| the file. Availability: Macintosh, Unix, Windows. |
| the file. Availability: Unix, Windows. |
| |
| |
| .. function:: open(file, flags[, mode]) |
| |
| Open the file *file* and set various flags according to *flags* and possibly its |
| mode according to *mode*. The default *mode* is ``0777`` (octal), and the |
| current umask value is first masked out. Return the file descriptor for the |
n | newly opened file. Availability: Macintosh, Unix, Windows. |
n | newly opened file. Availability: Unix, Windows. |
| |
| For a description of the flag and mode values, see the C run-time documentation; |
| flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in |
| this module too (see below). |
| |
| .. note:: |
| |
| This function is intended for low-level I/O. For normal usage, use the built-in |
| |
| |
| .. function:: openpty() |
| |
| .. index:: module: pty |
| |
| Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master, |
| slave)`` for the pty and the tty, respectively. For a (slightly) more portable |
n | approach, use the :mod:`pty` module. Availability: Macintosh, Some flavors of |
n | approach, use the :mod:`pty` module. Availability: some flavors of |
| Unix. |
| |
| |
| .. function:: pipe() |
| |
| Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading |
n | and writing, respectively. Availability: Macintosh, Unix, Windows. |
n | and writing, respectively. Availability: Unix, Windows. |
| |
| |
| .. function:: read(fd, n) |
| |
| Read at most *n* bytes from file descriptor *fd*. Return a string containing the |
| bytes read. If the end of the file referred to by *fd* has been reached, an |
n | empty string is returned. Availability: Macintosh, Unix, Windows. |
n | empty string is returned. Availability: Unix, Windows. |
| |
| .. note:: |
| |
| This function is intended for low-level I/O and must be applied to a file |
| descriptor as returned by :func:`open` or :func:`pipe`. To read a "file object" |
| returned by the built-in function :func:`open` or by :func:`popen` or |
n | :func:`fdopen`, or ``sys.stdin``, use its :meth:`read` or :meth:`readline` |
n | :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`read` or :meth:`readline` |
| methods. |
| |
| |
| .. function:: tcgetpgrp(fd) |
| |
| Return the process group associated with the terminal given by *fd* (an open |
n | file descriptor as returned by :func:`open`). Availability: Macintosh, Unix. |
n | file descriptor as returned by :func:`open`). Availability: Unix. |
| |
| |
| .. function:: tcsetpgrp(fd, pg) |
| |
| Set the process group associated with the terminal given by *fd* (an open file |
n | descriptor as returned by :func:`open`) to *pg*. Availability: Macintosh, Unix. |
n | descriptor as returned by :func:`open`) to *pg*. Availability: Unix. |
| |
| |
| .. function:: ttyname(fd) |
| |
n | Return a string which specifies the terminal device associated with file- |
n | Return a string which specifies the terminal device associated with |
| descriptor *fd*. If *fd* is not associated with a terminal device, an exception |
| file descriptor *fd*. If *fd* is not associated with a terminal device, an |
| is raised. Availability:Macintosh, Unix. |
| exception is raised. Availability: Unix. |
| |
| |
| .. function:: write(fd, str) |
| |
| Write the string *str* to file descriptor *fd*. Return the number of bytes |
n | actually written. Availability: Macintosh, Unix, Windows. |
n | actually written. Availability: Unix, Windows. |
| |
| .. note:: |
| |
| This function is intended for low-level I/O and must be applied to a file |
| descriptor as returned by :func:`open` or :func:`pipe`. To write a "file |
| object" returned by the built-in function :func:`open` or by :func:`popen` or |
n | :func:`fdopen`, or ``sys.stdout`` or ``sys.stderr``, use its :meth:`write` |
n | :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`write` |
| method. |
| |
n | The following data items are available for use in constructing the *flags* |
n | The following constants are options for the *flags* parameter to the |
| parameter to the :func:`open` function. Some items will not be available on all |
| :func:`open` function. They can be combined using the bitwise OR operator |
| platforms. For descriptions of their availability and use, consult |
| ``|``. Some of them are not available on all platforms. For descriptions of |
| :manpage:`open(2)`. |
| their availability and use, consult the :manpage:`open(2)` manual page on Unix |
| or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>` on Windows. |
| |
| |
| .. data:: O_RDONLY |
| O_WRONLY |
| O_RDWR |
| O_APPEND |
| O_CREAT |
| O_EXCL |
| O_TRUNC |
| |
n | Options for the *flag* argument to the :func:`open` function. These can be bit- |
n | These constants are available on Unix and Windows. |
| wise OR'd together. Availability: Macintosh, Unix, Windows. |
| |
| |
| .. data:: O_DSYNC |
| O_RSYNC |
| O_SYNC |
| O_NDELAY |
| O_NONBLOCK |
| O_NOCTTY |
| O_SHLOCK |
| O_EXLOCK |
| |
n | More options for the *flag* argument to the :func:`open` function. Availability: |
n | These constants are only available on Unix. |
| Macintosh, Unix. |
| |
| |
| .. data:: O_BINARY |
n | |
n | O_NOINHERIT |
| Option for the *flag* argument to the :func:`open` function. This can be bit- |
| wise OR'd together with those listed above. Availability: Windows. |
| |
| .. % XXX need to check on the availability of this one. |
| |
| |
| .. data:: O_NOINHERIT |
| O_SHORT_LIVED |
| O_TEMPORARY |
| O_RANDOM |
| O_SEQUENTIAL |
| O_TEXT |
| |
n | Options for the *flag* argument to the :func:`open` function. These can be bit- |
n | These constants are only available on Windows. |
| wise OR'd together. Availability: Windows. |
| |
| |
| .. data:: O_ASYNC |
| O_DIRECT |
| O_DIRECTORY |
| O_NOFOLLOW |
| O_NOATIME |
| |
| These constants are GNU extensions and not present if they are not defined by |
| the C library. |
| |
| |
| .. data:: SEEK_SET |
| SEEK_CUR |
| SEEK_END |
| |
| Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, |
n | respectively. Availability: Windows, Macintosh, Unix. |
n | respectively. Availability: Windows, Unix. |
| |
| .. versionadded:: 2.5 |
| |
| |
| .. _os-file-dir: |
| |
| Files and Directories |
| --------------------- |
n | |
| |
| .. function:: access(path, mode) |
| |
| Use the real uid/gid to test for access to *path*. Note that most operations |
| will use the effective uid/gid, therefore this routine can be used in a |
| suid/sgid environment to test if the invoking user has the specified access to |
| *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it |
| can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and |
| :const:`X_OK` to test permissions. Return :const:`True` if access is allowed, |
| :const:`False` if not. See the Unix man page :manpage:`access(2)` for more |
n | information. Availability: Macintosh, Unix, Windows. |
n | information. Availability: Unix, Windows. |
| |
| .. note:: |
| |
| Using :func:`access` to check if a user is authorized to e.g. open a file before |
| actually doing so using :func:`open` creates a security hole, because the user |
| might exploit the short time interval between checking and opening the file to |
| manipulate it. |
| |
| Value to include in the *mode* parameter of :func:`access` to determine if |
| *path* can be executed. |
| |
| |
| .. function:: chdir(path) |
| |
| .. index:: single: directory; changing |
| |
n | Change the current working directory to *path*. Availability: Macintosh, Unix, |
n | Change the current working directory to *path*. Availability: Unix, |
| Windows. |
| |
| |
| .. function:: fchdir(fd) |
| |
| Change the current working directory to the directory represented by the file |
| descriptor *fd*. The descriptor must refer to an opened directory, not an open |
| file. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: getcwd() |
| |
| Return a string representing the current working directory. Availability: |
n | Macintosh, Unix, Windows. |
n | Unix, Windows. |
| |
| |
| .. function:: getcwdu() |
| |
| Return a Unicode object representing the current working directory. |
n | Availability: Macintosh, Unix, Windows. |
n | Availability: Unix, Windows. |
| |
n | .. versionadded:: 2.3 |
| |
| |
| .. function:: chflags(path, flags) |
| |
| Set the flags of *path* to the numeric *flags*. *flags* may take a combination |
| (bitwise OR) of the following values (as defined in the :mod:`stat` module): |
| |
| * ``UF_NODUMP`` |
| * ``UF_IMMUTABLE`` |
| * ``UF_APPEND`` |
| * ``UF_OPAQUE`` |
| * ``UF_NOUNLINK`` |
| * ``SF_ARCHIVED`` |
| * ``SF_IMMUTABLE`` |
| * ``SF_APPEND`` |
| * ``SF_NOUNLINK`` |
| * ``SF_SNAPSHOT`` |
| |
| Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| .. versionadded:: 2.6 |
| |
| |
| .. function:: chroot(path) |
| |
| Change the root directory of the current process to *path*. Availability: |
n | Macintosh, Unix. |
n | Unix. |
| |
| .. versionadded:: 2.2 |
| |
| |
| .. function:: chmod(path, mode) |
| |
| Change the mode of *path* to the numeric *mode*. *mode* may take one of the |
n | following values (as defined in the :mod:`stat` module) or bitwise or-ed |
n | following values (as defined in the :mod:`stat` module) or bitwise ORed |
| combinations of them: |
| |
n | |
| * ``S_ISUID`` |
| * ``stat.S_ISUID`` |
| |
| * ``S_ISGID`` |
| * ``stat.S_ISGID`` |
| |
| * ``S_ENFMT`` |
| * ``stat.S_ENFMT`` |
| |
| * ``S_ISVTX`` |
| * ``stat.S_ISVTX`` |
| |
| * ``S_IREAD`` |
| * ``stat.S_IREAD`` |
| |
| * ``S_IWRITE`` |
| * ``stat.S_IWRITE`` |
| |
| * ``S_IEXEC`` |
| * ``stat.S_IEXEC`` |
| |
| * ``S_IRWXU`` |
| * ``stat.S_IRWXU`` |
| |
| * ``S_IRUSR`` |
| * ``stat.S_IRUSR`` |
| |
| * ``S_IWUSR`` |
| * ``stat.S_IWUSR`` |
| |
| * ``S_IXUSR`` |
| * ``stat.S_IXUSR`` |
| |
| * ``S_IRWXG`` |
| * ``stat.S_IRWXG`` |
| |
| * ``S_IRGRP`` |
| * ``stat.S_IRGRP`` |
| |
| * ``S_IWGRP`` |
| * ``stat.S_IWGRP`` |
| |
| * ``S_IXGRP`` |
| * ``stat.S_IXGRP`` |
| |
| * ``S_IRWXO`` |
| * ``stat.S_IRWXO`` |
| |
| * ``S_IROTH`` |
| * ``stat.S_IROTH`` |
| |
| * ``S_IWOTH`` |
| * ``stat.S_IWOTH`` |
| |
| * ``S_IXOTH`` |
| * ``stat.S_IXOTH`` |
| |
n | Availability: Macintosh, Unix, Windows. |
n | Availability: Unix, Windows. |
| |
| .. note:: |
| |
| Although Windows supports :func:`chmod`, you can only set the file's read-only |
n | flag with it (via the ``S_IWRITE`` and ``S_IREAD`` constants or a corresponding |
n | flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD`` |
| integer value). All other bits are ignored. |
| constants or a corresponding integer value). All other bits are |
| ignored. |
| |
| |
| .. function:: chown(path, uid, gid) |
| |
| Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave |
n | one of the ids unchanged, set it to -1. Availability: Macintosh, Unix. |
n | one of the ids unchanged, set it to -1. Availability: Unix. |
| |
| |
| .. function:: lchflags(path, flags) |
| |
| Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not |
| follow symbolic links. Availability: Unix. |
| |
| .. versionadded:: 2.6 |
| |
| |
| .. function:: lchmod(path, mode) |
| |
| Change the mode of *path* to the numeric *mode*. If path is a symlink, this |
| affects the symlink rather than the target. See the docs for :func:`chmod` |
| for possible values of *mode*. Availability: Unix. |
| |
| .. versionadded:: 2.6 |
| |
| |
| .. function:: lchown(path, uid, gid) |
| |
n | Change the owner and group id of *path* to the numeric *uid* and gid. This |
n | Change the owner and group id of *path* to the numeric *uid* and *gid*. This |
| function will not follow symbolic links. Availability: Macintosh, Unix. |
| function will not follow symbolic links. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: link(src, dst) |
| |
n | Create a hard link pointing to *src* named *dst*. Availability: Macintosh, Unix. |
n | Create a hard link pointing to *src* named *dst*. Availability: Unix. |
| |
| |
| .. function:: listdir(path) |
| |
n | Return a list containing the names of the entries in the directory. The list is |
n | Return a list containing the names of the entries in the directory given by |
| in arbitrary order. It does not include the special entries ``'.'`` and |
| *path*. The list is in arbitrary order. It does not include the special |
| ``'..'`` even if they are present in the directory. Availability: Macintosh, |
| entries ``'.'`` and ``'..'`` even if they are present in the |
| Unix, Windows. |
| directory. Availability: Unix, Windows. |
| |
| .. versionchanged:: 2.3 |
| On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be |
| a list of Unicode objects. |
| |
| |
| .. function:: lstat(path) |
| |
n | Like :func:`stat`, but do not follow symbolic links. Availability: Macintosh, |
n | Like :func:`stat`, but do not follow symbolic links. This is an alias for |
| Unix. |
| :func:`stat` on platforms that do not support symbolic links, such as |
| Windows. |
| |
| |
| .. function:: mkfifo(path[, mode]) |
| |
| Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default |
| *mode* is ``0666`` (octal). The current umask value is first masked out from |
n | the mode. Availability: Macintosh, Unix. |
n | the mode. Availability: Unix. |
| |
| FIFOs are pipes that can be accessed like regular files. FIFOs exist until they |
| are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as |
| rendezvous between "client" and "server" type processes: the server opens the |
| FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo` |
| doesn't open the FIFO --- it just creates the rendezvous point. |
| |
| |
| .. function:: mknod(filename[, mode=0600, device]) |
| |
| Create a filesystem node (file, device special file or named pipe) named |
| *filename*. *mode* specifies both the permissions to use and the type of node to |
n | be created, being combined (bitwise OR) with one of S_IFREG, S_IFCHR, S_IFBLK, |
n | be created, being combined (bitwise OR) with one of ``stat.S_IFREG``, |
| ``stat.S_IFCHR``, ``stat.S_IFBLK``, |
| and S_IFIFO (those constants are available in :mod:`stat`). For S_IFCHR and |
| and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`). |
| For ``stat.S_IFCHR`` and |
| S_IFBLK, *device* defines the newly created device special file (probably using |
| ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using |
| :func:`os.makedev`), otherwise it is ignored. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: major(device) |
| |
n | Extracts the device major number from a raw device number (usually the |
n | Extract the device major number from a raw device number (usually the |
| :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`). |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: minor(device) |
| |
n | Extracts the device minor number from a raw device number (usually the |
n | Extract the device minor number from a raw device number (usually the |
| :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`). |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: makedev(major, minor) |
| |
n | Composes a raw device number from the major and minor device numbers. |
n | Compose a raw device number from the major and minor device numbers. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: mkdir(path[, mode]) |
| |
| Create a directory named *path* with numeric mode *mode*. The default *mode* is |
| ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the |
n | current umask value is first masked out. Availability: Macintosh, Unix, Windows. |
n | current umask value is first masked out. Availability: Unix, Windows. |
| |
| It is also possible to create temporary directories; see the |
| :mod:`tempfile` module's :func:`tempfile.mkdtemp` function. |
| |
| |
| .. function:: makedirs(path[, mode]) |
| |
| .. index:: |
| single: directory; creating |
| single: UNC paths; and os.makedirs() |
| |
| intermediate-level directories needed to contain the leaf directory. Throws an |
| :exc:`error` exception if the leaf directory already exists or cannot be |
| created. The default *mode* is ``0777`` (octal). On some systems, *mode* is |
| ignored. Where it is used, the current umask value is first masked out. |
| |
| .. note:: |
| |
| :func:`makedirs` will become confused if the path elements to create include |
n | *os.pardir*. |
n | :data:`os.pardir`. |
| |
| .. versionadded:: 1.5.2 |
| |
| .. versionchanged:: 2.3 |
| This function now handles UNC paths correctly. |
| |
| |
| .. function:: pathconf(path, name) |
| |
| Return system configuration information relevant to a named file. *name* |
| specifies the configuration value to retrieve; it may be a string which is the |
| name of a defined system value; these names are specified in a number of |
| standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define |
| additional names as well. The names known to the host operating system are |
| given in the ``pathconf_names`` dictionary. For configuration variables not |
| included in that mapping, passing an integer for *name* is also accepted. |
n | Availability: Macintosh, Unix. |
n | Availability: Unix. |
| |
| If *name* is a string and is not known, :exc:`ValueError` is raised. If a |
| specific value for *name* is not supported by the host system, even if it is |
| included in ``pathconf_names``, an :exc:`OSError` is raised with |
| :const:`errno.EINVAL` for the error number. |
| |
| |
| .. data:: pathconf_names |
| |
| Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to |
| the integer values defined for those names by the host operating system. This |
| can be used to determine the set of names known to the system. Availability: |
n | Macintosh, Unix. |
n | Unix. |
| |
| |
| .. function:: readlink(path) |
| |
| Return a string representing the path to which the symbolic link points. The |
| result may be either an absolute or relative pathname; if it is relative, it may |
| be converted to an absolute pathname using ``os.path.join(os.path.dirname(path), |
n | result)``. Availability: Macintosh, Unix. |
n | result)``. |
| |
| .. versionchanged:: 2.6 |
| If the *path* is a Unicode object the result will also be a Unicode object. |
| |
| Availability: Unix. |
| |
| |
| .. function:: remove(path) |
| |
| Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see |
| :func:`rmdir` below to remove a directory. This is identical to the |
| :func:`unlink` function documented below. On Windows, attempting to remove a |
| file that is in use causes an exception to be raised; on Unix, the directory |
| entry is removed but the storage allocated to the file is not made available |
n | until the original file is no longer in use. Availability: Macintosh, Unix, |
n | until the original file is no longer in use. Availability: Unix, |
| Windows. |
| |
| |
| .. function:: removedirs(path) |
| |
| .. index:: single: directory; deleting |
| |
n | Removes directories recursively. Works like :func:`rmdir` except that, if the |
n | Remove directories recursively. Works like :func:`rmdir` except that, if the |
| leaf directory is successfully removed, :func:`removedirs` tries to |
| successively remove every parent directory mentioned in *path* until an error |
| is raised (which is ignored, because it generally means that a parent directory |
| is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove |
| the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if |
| they are empty. Raises :exc:`OSError` if the leaf directory could not be |
| successfully removed. |
| |
| .. versionadded:: 1.5.2 |
| |
| |
| .. function:: rename(src, dst) |
| |
| Rename the file or directory *src* to *dst*. If *dst* is a directory, |
| :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will |
n | be removed silently if the user has permission. The operation may fail on some |
n | be replaced silently if the user has permission. The operation may fail on some |
| Unix flavors if *src* and *dst* are on different filesystems. If successful, |
| the renaming will be an atomic operation (this is a POSIX requirement). On |
| Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a |
| file; there may be no way to implement an atomic rename when *dst* names an |
n | existing file. Availability: Macintosh, Unix, Windows. |
n | existing file. Availability: Unix, Windows. |
| |
| |
| .. function:: renames(old, new) |
| |
| Recursive directory or file renaming function. Works like :func:`rename`, except |
| creation of any intermediate directories needed to make the new pathname good is |
| attempted first. After the rename, directories corresponding to rightmost path |
| segments of the old name will be pruned away using :func:`removedirs`. |
| .. note:: |
| |
| This function can fail with the new directory structure made if you lack |
| permissions needed to remove the leaf directory or file. |
| |
| |
| .. function:: rmdir(path) |
| |
n | Remove the directory *path*. Availability: Macintosh, Unix, Windows. |
n | Remove the directory *path*. Availability: Unix, Windows. |
| |
| |
| .. function:: stat(path) |
| |
| Perform a :cfunc:`stat` system call on the given path. The return value is an |
| object whose attributes correspond to the members of the :ctype:`stat` |
| structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode |
| number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links), |
n | :attr:`st_uid` (user ID of owner), :attr:`st_gid` (group ID of owner), |
n | :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner), |
| :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent |
| access), :attr:`st_mtime` (time of most recent content modification), |
| :attr:`st_ctime` (platform dependent; time of most recent metadata change on |
| Unix, or the time of creation on Windows):: |
| |
| >>> import os |
| >>> statinfo = os.stat('somefile.txt') |
| >>> statinfo |
| (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732) |
| >>> statinfo.st_size |
| 926L |
| >>> |
| |
| .. versionchanged:: 2.3 |
n | If :func:`stat_float_times` returns true, the time values are floats, measuring |
n | If :func:`stat_float_times` returns ``True``, the time values are floats, measuring |
| seconds. Fractions of a second may be reported if the system supports that. On |
| Mac OS, the times are always floats. See :func:`stat_float_times` for further |
| discussion. |
| |
| On some Unix systems (such as Linux), the following attributes may also be |
| available: :attr:`st_blocks` (number of blocks allocated for file), |
| :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an |
| inode device). :attr:`st_flags` (user defined flags for file). |
| |
| The maximum number of unique names that :func:`tmpnam` will generate before |
| reusing names. |
| |
| |
| .. function:: unlink(path) |
| |
| Remove the file *path*. This is the same function as :func:`remove`; the |
n | :func:`unlink` name is its traditional Unix name. Availability: Macintosh, Unix, |
n | :func:`unlink` name is its traditional Unix name. Availability: Unix, |
| Windows. |
| |
| |
| .. function:: utime(path, times) |
| |
n | Set the access and modified times of the file specified by *path*. If *times* is |
n | Set the access and modified times of the file specified by *path*. If *times* |
| ``None``, then the file's access and modified times are set to the current time. |
| is ``None``, then the file's access and modified times are set to the current |
| time. (The effect is similar to running the Unix program :program:`touch` on |
| Otherwise, *times* must be a 2-tuple of numbers, of the form ``(atime, mtime)`` |
| the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form |
| which is used to set the access and modified times, respectively. Whether a |
| ``(atime, mtime)`` which is used to set the access and modified times, |
| directory can be given for *path* depends on whether the operating system |
| respectively. Whether a directory can be given for *path* depends on whether |
| implements directories as files (for example, Windows does not). Note that the |
| the operating system implements directories as files (for example, Windows |
| exact times you set here may not be returned by a subsequent :func:`stat` call, |
| does not). Note that the exact times you set here may not be returned by a |
| depending on the resolution with which your operating system records access and |
| subsequent :func:`stat` call, depending on the resolution with which your |
| modification times; see :func:`stat`. |
| operating system records access and modification times; see :func:`stat`. |
| |
| .. versionchanged:: 2.0 |
| Added support for ``None`` for *times*. |
| |
n | Availability: Macintosh, Unix, Windows. |
n | Availability: Unix, Windows. |
| |
| |
n | .. function:: walk(top[, topdown\ ``=True`` [, onerror\ ``=None``]]) |
n | .. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]]) |
| |
| .. index:: |
| single: directory; walking |
| single: directory; traversal |
| |
n | :func:`walk` generates the file names in a directory tree, by walking the tree |
n | Generate the file names in a directory tree by walking the tree |
| either top down or bottom up. For each directory in the tree rooted at directory |
| either top-down or bottom-up. For each directory in the tree rooted at directory |
| *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames, |
| filenames)``. |
| |
| *dirpath* is a string, the path to the directory. *dirnames* is a list of the |
| names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``). |
| *filenames* is a list of the names of the non-directory files in *dirpath*. |
| Note that the names in the lists contain no path components. To get a full path |
| (which begins with *top*) to a file or directory in *dirpath*, do |
| ``os.path.join(dirpath, name)``. |
| |
n | If optional argument *topdown* is true or not specified, the triple for a |
n | If optional argument *topdown* is ``True`` or not specified, the triple for a |
| directory is generated before the triples for any of its subdirectories |
n | (directories are generated top down). If *topdown* is false, the triple for a |
n | (directories are generated top-down). If *topdown* is ``False``, the triple for a |
| directory is generated after the triples for all of its subdirectories |
n | (directories are generated bottom up). |
n | (directories are generated bottom-up). |
| |
n | When *topdown* is true, the caller can modify the *dirnames* list in-place |
n | When *topdown* is ``True``, the caller can modify the *dirnames* list in-place |
| (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only |
| recurse into the subdirectories whose names remain in *dirnames*; this can be |
| used to prune the search, impose a specific order of visiting, or even to inform |
| :func:`walk` about directories the caller creates or renames before it resumes |
n | :func:`walk` again. Modifying *dirnames* when *topdown* is false is |
n | :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is |
| ineffective, because in bottom-up mode the directories in *dirnames* are |
| generated before *dirpath* itself is generated. |
| |
n | By default errors from the ``os.listdir()`` call are ignored. If optional |
n | By default errors from the :func:`listdir` call are ignored. If optional |
| argument *onerror* is specified, it should be a function; it will be called with |
| one argument, an :exc:`OSError` instance. It can report the error to continue |
| with the walk, or raise the exception to abort the walk. Note that the filename |
| is available as the ``filename`` attribute of the exception object. |
| |
n | By default, :func:`walk` will not walk down into symbolic links that resolve to |
| directories. Set *followlinks* to ``True`` to visit directories pointed to by |
| symlinks, on systems that support them. |
| |
| .. versionadded:: 2.6 |
| The *followlinks* parameter. |
| |
| .. note:: |
| |
| Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a |
| link points to a parent directory of itself. :func:`walk` does not keep track of |
| the directories it visited already. |
| |
| .. note:: |
| |
| If you pass a relative pathname, don't change the current working directory |
| between resumptions of :func:`walk`. :func:`walk` never changes the current |
| directory, and assumes that its caller doesn't either. |
n | |
| .. note:: |
| |
| On systems that support symbolic links, links to subdirectories appear in |
| *dirnames* lists, but :func:`walk` will not visit them (infinite loops are hard |
| to avoid when following symbolic links). To visit linked directories, you can |
| identify them with ``os.path.islink(path)``, and invoke ``walk(path)`` on each |
| directly. |
| |
| This example displays the number of bytes taken by non-directory files in each |
| directory under the starting directory, except that it doesn't look under any |
| CVS subdirectory:: |
| |
| import os |
| from os.path import join, getsize |
| for root, dirs, files in os.walk('python/Lib/email'): |
| print root, "consumes", |
| print sum(getsize(join(root, name)) for name in files), |
| print "bytes in", len(files), "non-directory files" |
| if 'CVS' in dirs: |
| dirs.remove('CVS') # don't visit CVS directories |
| |
n | In the next example, walking the tree bottom up is essential: :func:`rmdir` |
n | In the next example, walking the tree bottom-up is essential: :func:`rmdir` |
| doesn't allow deleting a directory before the directory is empty:: |
| |
n | # Delete everything reachable from the directory named in 'top', |
n | # Delete everything reachable from the directory named in "top", |
| # assuming there are no symbolic links. |
| # CAUTION: This is dangerous! For example, if top == '/', it |
| # could delete all your disk files. |
| import os |
| for root, dirs, files in os.walk(top, topdown=False): |
| for name in files: |
| os.remove(os.path.join(root, name)) |
| for name in dirs: |
| |
| |
| .. function:: abort() |
| |
| Generate a :const:`SIGABRT` signal to the current process. On Unix, the default |
| behavior is to produce a core dump; on Windows, the process immediately returns |
| an exit code of ``3``. Be aware that programs which use :func:`signal.signal` |
| to register a handler for :const:`SIGABRT` will behave differently. |
n | Availability: Macintosh, Unix, Windows. |
n | Availability: Unix, Windows. |
| |
| |
| .. function:: execl(path, arg0, arg1, ...) |
| execle(path, arg0, arg1, ..., env) |
| execlp(file, arg0, arg1, ...) |
| execlpe(file, arg0, arg1, ..., env) |
| execv(path, args) |
| execve(path, args, env) |
| execvp(file, args) |
| execvpe(file, args, env) |
| |
| These functions all execute a new program, replacing the current process; they |
| do not return. On Unix, the new executable is loaded into the current process, |
n | and will have the same process ID as the caller. Errors will be reported as |
n | and will have the same process id as the caller. Errors will be reported as |
| :exc:`OSError` exceptions. |
| |
n | The current process is replaced immediately. Open file objects and |
| descriptors are not flushed, so if there may be data buffered |
| on these open files, you should flush them using |
| :func:`sys.stdout.flush` or :func:`os.fsync` before calling an |
| :func:`exec\*` function. |
| |
| The ``'l'`` and ``'v'`` variants of the :func:`exec\*` functions differ in how |
| The "l" and "v" variants of the :func:`exec\*` functions differ in how |
| command-line arguments are passed. The ``'l'`` variants are perhaps the easiest |
| command-line arguments are passed. The "l" variants are perhaps the easiest |
| to work with if the number of parameters is fixed when the code is written; the |
| individual parameters simply become additional parameters to the :func:`execl\*` |
n | functions. The ``'v'`` variants are good when the number of parameters is |
n | functions. The "v" variants are good when the number of parameters is |
| variable, with the arguments being passed in a list or tuple as the *args* |
| parameter. In either case, the arguments to the child process should start with |
| the name of the command being run, but this is not enforced. |
| |
n | The variants which include a ``'p'`` near the end (:func:`execlp`, |
n | The variants which include a "p" near the end (:func:`execlp`, |
| :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the |
| :envvar:`PATH` environment variable to locate the program *file*. When the |
| environment is being replaced (using one of the :func:`exec\*e` variants, |
| discussed in the next paragraph), the new environment is used as the source of |
| the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`, |
| :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to |
| locate the executable; *path* must contain an appropriate absolute or relative |
| path. |
| |
| For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note |
n | that these all end in ``'e'``), the *env* parameter must be a mapping which is |
n | that these all end in "e"), the *env* parameter must be a mapping which is |
| used to define the environment variables for the new process; the :func:`execl`, |
| used to define the environment variables for the new process (these are used |
| instead of the current process' environment); the functions :func:`execl`, |
| :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to |
n | inherit the environment of the current process. Availability: Macintosh, Unix, |
n | inherit the environment of the current process. |
| Windows. |
| |
| Availability: Unix, Windows. |
| |
| |
| .. function:: _exit(n) |
| |
| Exit to the system with status *n*, without calling cleanup handlers, flushing |
n | stdio buffers, etc. Availability: Macintosh, Unix, Windows. |
n | stdio buffers, etc. Availability: Unix, Windows. |
| |
| .. note:: |
| |
| The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only |
| be used in the child process after a :func:`fork`. |
| |
n | The following exit codes are a defined, and can be used with :func:`_exit`, |
n | The following exit codes are defined and can be used with :func:`_exit`, |
| although they are not required. These are typically used for system programs |
| written in Python, such as a mail server's external command delivery program. |
| |
| .. note:: |
| |
| Some of these may not be available on all Unix platforms, since there is some |
| variation. These constants are defined where they are defined by the underlying |
| platform. |
| |
| |
| .. data:: EX_OK |
| |
n | Exit code that means no error occurred. Availability: Macintosh, Unix. |
n | Exit code that means no error occurred. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_USAGE |
| |
| Exit code that means the command was used incorrectly, such as when the wrong |
n | number of arguments are given. Availability: Macintosh, Unix. |
n | number of arguments are given. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_DATAERR |
| |
n | Exit code that means the input data was incorrect. Availability: Macintosh, |
n | Exit code that means the input data was incorrect. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_NOINPUT |
| |
| Exit code that means an input file did not exist or was not readable. |
| Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_NOUSER |
| |
| Exit code that means a specified user did not exist. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_NOHOST |
| |
| Exit code that means a specified host did not exist. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_UNAVAILABLE |
| |
| Exit code that means that a required service is unavailable. Availability: |
| Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
n | .. data:: EX_NOINPUT |
| |
| Exit code that means an input file did not exist or was not readable. |
| Availability: Macintosh, Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_NOUSER |
| .. data:: EX_SOFTWARE |
| |
n | Exit code that means a specified user did not exist. Availability: Macintosh, |
n | Exit code that means an internal software error was detected. Availability: |
| Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
n | .. data:: EX_NOHOST |
| |
| Exit code that means a specified host did not exist. Availability: Macintosh, |
| Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_UNAVAILABLE |
| |
| Exit code that means that a required service is unavailable. Availability: |
| Macintosh, Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_SOFTWARE |
| |
| Exit code that means an internal software error was detected. Availability: |
| Macintosh, Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_OSERR |
| |
| Exit code that means an operating system error was detected, such as the |
n | inability to fork or create a pipe. Availability: Macintosh, Unix. |
n | inability to fork or create a pipe. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_OSFILE |
| |
| Exit code that means some system file did not exist, could not be opened, or had |
n | some other kind of error. Availability: Macintosh, Unix. |
n | some other kind of error. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_CANTCREAT |
| |
| Exit code that means a user specified output file could not be created. |
n | Availability: Macintosh, Unix. |
n | Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_IOERR |
| |
| Exit code that means that an error occurred while doing I/O on some file. |
n | Availability: Macintosh, Unix. |
n | Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_TEMPFAIL |
| |
| Exit code that means a temporary failure occurred. This indicates something |
| that may not really be an error, such as a network connection that couldn't be |
n | made during a retryable operation. Availability: Macintosh, Unix. |
n | made during a retryable operation. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_PROTOCOL |
| |
| Exit code that means that a protocol exchange was illegal, invalid, or not |
n | understood. Availability: Macintosh, Unix. |
n | understood. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_NOPERM |
| |
| Exit code that means that there were insufficient permissions to perform the |
n | operation (but not intended for file system problems). Availability: Macintosh, |
n | operation (but not intended for file system problems). Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_CONFIG |
| |
| Exit code that means that some kind of configuration error occurred. |
| Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_NOTFOUND |
| |
| Exit code that means something like "an entry was not found". Availability: |
| Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
n | .. data:: EX_CONFIG |
| |
| Exit code that means that some kind of configuration error occurred. |
| Availability: Macintosh, Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: EX_NOTFOUND |
| |
| Exit code that means something like "an entry was not found". Availability: |
| Macintosh, Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: fork() |
| |
n | Fork a child process. Return ``0`` in the child, the child's process id in the |
n | Fork a child process. Return ``0`` in the child and the child's process id in the |
| parent. Availability: Macintosh, Unix. |
| parent. If an error occurs :exc:`OSError` is raised. |
| |
| Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have |
| known issues when using fork() from a thread. |
| |
| Availability: Unix. |
| |
| |
| .. function:: forkpty() |
| |
| Fork a child process, using a new pseudo-terminal as the child's controlling |
| terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the |
| new child's process id in the parent, and *fd* is the file descriptor of the |
| master end of the pseudo-terminal. For a more portable approach, use the |
n | :mod:`pty` module. Availability: Macintosh, Some flavors of Unix. |
n | :mod:`pty` module. If an error occurs :exc:`OSError` is raised. |
| Availability: some flavors of Unix. |
| |
| |
| .. function:: kill(pid, sig) |
| |
| .. index:: |
| single: process; killing |
| single: process; signalling |
| |
| Send signal *sig* to the process *pid*. Constants for the specific signals |
| available on the host platform are defined in the :mod:`signal` module. |
n | Availability: Macintosh, Unix. |
n | Availability: Unix. |
| |
| |
| .. function:: killpg(pgid, sig) |
| |
| .. index:: |
| single: process; killing |
| single: process; signalling |
| |
n | Send the signal *sig* to the process group *pgid*. Availability: Macintosh, |
n | Send the signal *sig* to the process group *pgid*. Availability: Unix. |
| Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: nice(increment) |
| |
| Add *increment* to the process's "niceness". Return the new niceness. |
n | Availability: Macintosh, Unix. |
n | Availability: Unix. |
| |
| |
| .. function:: plock(op) |
| |
| Lock program segments into memory. The value of *op* (defined in |
n | ``<sys/lock.h>``) determines which segments are locked. Availability: Macintosh, |
n | ``<sys/lock.h>``) determines which segments are locked. Availability: Unix. |
| Unix. |
| |
| |
| .. function:: popen(...) |
| popen2(...) |
| popen3(...) |
| popen4(...) |
| :noindex: |
| |
| spawnle(mode, path, ..., env) |
| spawnlp(mode, file, ...) |
| spawnlpe(mode, file, ..., env) |
| spawnv(mode, path, args) |
| spawnve(mode, path, args, env) |
| spawnvp(mode, file, args) |
| spawnvpe(mode, file, args, env) |
| |
n | Execute the program *path* in a new process. If *mode* is :const:`P_NOWAIT`, |
n | Execute the program *path* in a new process. |
| this function returns the process ID of the new process; if *mode* is |
| |
| :const:`P_WAIT`, returns the process's exit code if it exits normally, or |
| (Note that the :mod:`subprocess` module provides more powerful facilities for |
| ``-signal``, where *signal* is the signal that killed the process. On Windows, |
| spawning new processes and retrieving their results; using that module is |
| the process ID will actually be the process handle, so can be used with the |
| preferable to using these functions. Check specially the *Replacing Older |
| Functions with the subprocess Module* section in that documentation page.) |
| |
| If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new |
| process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it |
| exits normally, or ``-signal``, where *signal* is the signal that killed the |
| process. On Windows, the process id will actually be the process handle, so can |
| :func:`waitpid` function. |
| be used with the :func:`waitpid` function. |
| |
n | The ``'l'`` and ``'v'`` variants of the :func:`spawn\*` functions differ in how |
n | The "l" and "v" variants of the :func:`spawn\*` functions differ in how |
| command-line arguments are passed. The ``'l'`` variants are perhaps the easiest |
| command-line arguments are passed. The "l" variants are perhaps the easiest |
| to work with if the number of parameters is fixed when the code is written; the |
| individual parameters simply become additional parameters to the |
n | :func:`spawnl\*` functions. The ``'v'`` variants are good when the number of |
n | :func:`spawnl\*` functions. The "v" variants are good when the number of |
| parameters is variable, with the arguments being passed in a list or tuple as |
| the *args* parameter. In either case, the arguments to the child process must |
| start with the name of the command being run. |
| |
n | The variants which include a second ``'p'`` near the end (:func:`spawnlp`, |
n | The variants which include a second "p" near the end (:func:`spawnlp`, |
| :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the |
| :envvar:`PATH` environment variable to locate the program *file*. When the |
| environment is being replaced (using one of the :func:`spawn\*e` variants, |
| discussed in the next paragraph), the new environment is used as the source of |
| the :envvar:`PATH` variable. The other variants, :func:`spawnl`, |
| :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the |
| :envvar:`PATH` variable to locate the executable; *path* must contain an |
| appropriate absolute or relative path. |
| |
| For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe` |
n | (note that these all end in ``'e'``), the *env* parameter must be a mapping |
n | (note that these all end in "e"), the *env* parameter must be a mapping |
| which is used to define the environment variables for the new process; the |
| which is used to define the environment variables for the new process (they are |
| used instead of the current process' environment); the functions |
| :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause |
n | the new process to inherit the environment of the current process. |
n | the new process to inherit the environment of the current process. Note that |
| keys and values in the *env* dictionary must be strings; invalid keys or |
| values will cause the function to fail, with a return value of ``127``. |
| |
| As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are |
| equivalent:: |
| |
| import os |
| os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') |
| |
| L = ['cp', 'index.html', '/dev/null'] |
| .. versionadded:: 2.5 |
| The *operation* parameter. |
| |
| |
| .. function:: system(command) |
| |
| Execute the command (a string) in a subshell. This is implemented by calling |
| the Standard C function :cfunc:`system`, and has the same limitations. Changes |
n | to ``posix.environ``, ``sys.stdin``, etc. are not reflected in the environment |
n | to :data:`os.environ`, :data:`sys.stdin`, etc. are not reflected in the |
| of the executed command. |
| environment of the executed command. |
| |
| On Unix, the return value is the exit status of the process encoded in the |
| format specified for :func:`wait`. Note that POSIX does not specify the meaning |
| of the return value of the C :cfunc:`system` function, so the return value of |
| the Python function is system-dependent. |
| |
| On Windows, the return value is that returned by the system shell after running |
| *command*, given by the Windows environment variable :envvar:`COMSPEC`: on |
| :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on |
| :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of |
| the command run; on systems using a non-native shell, consult your shell |
| documentation. |
| |
n | Availability: Macintosh, Unix, Windows. |
n | Availability: Unix, Windows. |
| |
| The :mod:`subprocess` module provides more powerful facilities for spawning new |
| processes and retrieving their results; using that module is preferable to using |
| this function. Use the :mod:`subprocess` module. Check especially the |
| :ref:`subprocess-replacements` section. |
| |
| |
| .. function:: times() |
| |
| Return a 5-tuple of floating point numbers indicating accumulated (processor or |
| other) times, in seconds. The items are: user time, system time, children's |
| user time, children's system time, and elapsed real time since a fixed point in |
| the past, in that order. See the Unix manual page :manpage:`times(2)` or the |
n | corresponding Windows Platform API documentation. Availability: Macintosh, Unix, |
n | corresponding Windows Platform API documentation. Availability: Unix, |
| Windows. |
| Windows. On Windows, only the first two items are filled, the others are zero. |
| |
| |
| .. function:: wait() |
| |
| Wait for completion of a child process, and return a tuple containing its pid |
| and exit status indication: a 16-bit number, whose low byte is the signal number |
| that killed the process, and whose high byte is the exit status (if the signal |
| number is zero); the high bit of the low byte is set if a core file was |
n | produced. Availability: Macintosh, Unix. |
n | produced. Availability: Unix. |
| |
| |
| .. function:: waitpid(pid, options) |
| |
| The details of this function differ on Unix and Windows. |
| |
| On Unix: Wait for completion of a child process given by process id *pid*, and |
| return a tuple containing its process id and exit status indication (encoded as |
| |
| .. versionadded:: 2.5 |
| |
| |
| .. data:: WNOHANG |
| |
| The option for :func:`waitpid` to return immediately if no child process status |
| is available immediately. The function returns ``(0, 0)`` in this case. |
n | Availability: Macintosh, Unix. |
n | Availability: Unix. |
| |
| |
| .. data:: WCONTINUED |
| |
| This option causes child processes to be reported if they have been continued |
| from a job control stop since their status was last reported. Availability: Some |
| Unix systems. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. data:: WUNTRACED |
| |
| This option causes child processes to be reported if they have been stopped but |
| their current state has not been reported since they were stopped. Availability: |
n | Macintosh, Unix. |
n | Unix. |
| |
| .. versionadded:: 2.3 |
| |
| The following functions take a process status code as returned by |
| :func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be |
| used to determine the disposition of a process. |
| |
| |
| .. function:: WCOREDUMP(status) |
| |
n | Returns ``True`` if a core dump was generated for the process, otherwise it |
n | Return ``True`` if a core dump was generated for the process, otherwise |
| returns ``False``. Availability: Macintosh, Unix. |
| return ``False``. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: WIFCONTINUED(status) |
| |
n | Returns ``True`` if the process has been continued from a job control stop, |
n | Return ``True`` if the process has been continued from a job control stop, |
| otherwise it returns ``False``. Availability: Unix. |
| otherwise return ``False``. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: WIFSTOPPED(status) |
| |
n | Returns ``True`` if the process has been stopped, otherwise it returns |
n | Return ``True`` if the process has been stopped, otherwise return |
| ``False``. Availability: Unix. |
| |
| |
| .. function:: WIFSIGNALED(status) |
| |
n | Returns ``True`` if the process exited due to a signal, otherwise it returns |
n | Return ``True`` if the process exited due to a signal, otherwise return |
| ``False``. Availability: Macintosh, Unix. |
| ``False``. Availability: Unix. |
| |
| |
| .. function:: WIFEXITED(status) |
| |
n | Returns ``True`` if the process exited using the :manpage:`exit(2)` system call, |
n | Return ``True`` if the process exited using the :manpage:`exit(2)` system call, |
| otherwise it returns ``False``. Availability: Macintosh, Unix. |
| otherwise return ``False``. Availability: Unix. |
| |
| |
| .. function:: WEXITSTATUS(status) |
| |
| If ``WIFEXITED(status)`` is true, return the integer parameter to the |
| :manpage:`exit(2)` system call. Otherwise, the return value is meaningless. |
n | Availability: Macintosh, Unix. |
n | Availability: Unix. |
| |
| |
| .. function:: WSTOPSIG(status) |
| |
n | Return the signal which caused the process to stop. Availability: Macintosh, |
n | Return the signal which caused the process to stop. Availability: Unix. |
| Unix. |
| |
| |
| .. function:: WTERMSIG(status) |
| |
n | Return the signal which caused the process to exit. Availability: Macintosh, |
n | Return the signal which caused the process to exit. Availability: Unix. |
| Unix. |
| |
| |
| .. _os-path: |
| |
| Miscellaneous System Information |
| -------------------------------- |
| |
| |
| |
| Return string-valued system configuration values. *name* specifies the |
| configuration value to retrieve; it may be a string which is the name of a |
| defined system value; these names are specified in a number of standards (POSIX, |
| Unix 95, Unix 98, and others). Some platforms define additional names as well. |
| The names known to the host operating system are given as the keys of the |
| ``confstr_names`` dictionary. For configuration variables not included in that |
| mapping, passing an integer for *name* is also accepted. Availability: |
n | Macintosh, Unix. |
n | Unix. |
| |
| If the configuration value specified by *name* isn't defined, ``None`` is |
| returned. |
| |
| If *name* is a string and is not known, :exc:`ValueError` is raised. If a |
| specific value for *name* is not supported by the host system, even if it is |
| included in ``confstr_names``, an :exc:`OSError` is raised with |
| :const:`errno.EINVAL` for the error number. |
| |
| |
| .. data:: confstr_names |
| |
| Dictionary mapping names accepted by :func:`confstr` to the integer values |
| defined for those names by the host operating system. This can be used to |
n | determine the set of names known to the system. Availability: Macintosh, Unix. |
n | determine the set of names known to the system. Availability: Unix. |
| |
| |
| .. function:: getloadavg() |
| |
n | Return the number of processes in the system run queue averaged over the last 1, |
n | Return the number of processes in the system run queue averaged over the last |
| 5, and 15 minutes or raises :exc:`OSError` if the load average was |
| 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was |
| unobtainable. |
| unobtainable. Availability: Unix. |
| |
| .. versionadded:: 2.3 |
| |
| |
| .. function:: sysconf(name) |
| |
| Return integer-valued system configuration values. If the configuration value |
| specified by *name* isn't defined, ``-1`` is returned. The comments regarding |
| the *name* parameter for :func:`confstr` apply here as well; the dictionary that |
| provides information on the known names is given by ``sysconf_names``. |
n | Availability: Macintosh, Unix. |
n | Availability: Unix. |
| |
| |
| .. data:: sysconf_names |
| |
| Dictionary mapping names accepted by :func:`sysconf` to the integer values |
| defined for those names by the host operating system. This can be used to |
n | determine the set of names known to the system. Availability: Macintosh, Unix. |
n | determine the set of names known to the system. Availability: Unix. |
| |
n | The follow data values are used to support path manipulation operations. These |
n | The following data values are used to support path manipulation operations. These |
| are defined for all platforms. |
| |
| Higher-level operations on pathnames are defined in the :mod:`os.path` module. |
| |
| |
| .. data:: curdir |
| |
| The constant string used by the operating system to refer to the current |
n | directory. For example: ``'.'`` for POSIX or ``':'`` for Mac OS 9. Also |
n | directory. This is ``'.'`` for Windows and POSIX. Also available via |
| available via :mod:`os.path`. |
| :mod:`os.path`. |
| |
| |
| .. data:: pardir |
| |
| The constant string used by the operating system to refer to the parent |
n | directory. For example: ``'..'`` for POSIX or ``'::'`` for Mac OS 9. Also |
n | directory. This is ``'..'`` for Windows and POSIX. Also available via |
| available via :mod:`os.path`. |
| :mod:`os.path`. |
| |
| |
| .. data:: sep |
| |
n | The character used by the operating system to separate pathname components, for |
n | The character used by the operating system to separate pathname components. |
| example, ``'/'`` for POSIX or ``':'`` for Mac OS 9. Note that knowing this is |
| This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this |
| not sufficient to be able to parse or concatenate pathnames --- use |
| is not sufficient to be able to parse or concatenate pathnames --- use |
| :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally |
| useful. Also available via :mod:`os.path`. |
| |
| |
| .. data:: altsep |
| |
| An alternative character used by the operating system to separate pathname |
| components, or ``None`` if only one separator character exists. This is set to |