15.1. os — Miscellaneous operating system interfaces

This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module.

Notes on the availability of these functions:

  • The design of all built-in operating system dependent modules of Python is such that as long as the same functionality is available, it uses the same interface; for example, the function os.stat(path) returns stat information about 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 os module, but using them is of course a threat to portability.

  • An “Availability: Unix” note means that this function is commonly found on Unix systems. It does not make any claims about its existence on a specific operating system.

  • If not separately noted, all functions that claim “Availability: Unix” are supported on Mac OS X, which builds on a Unix core.

Note

All functions in this module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.

exception os.error

An alias for the built-in OSError exception.

os.name

The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'os2', 'ce', 'java', 'riscos'.

See also

sys.platform has a finer granularity. os.uname() gives system-dependent version information.

The platform module provides detailed checks for the system’s identity.

15.1.1. Process Parameters

These functions and data items provide information and operate on the current process and user.

os.environ

A mapping object representing the string environment. For example, environ['HOME'] is the pathname of your home directory (on some platforms), and is equivalent to getenv("HOME") in C.

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.

If the platform supports the putenv() function, this mapping may be used to modify the environment as well as query the environment. putenv() will be called automatically when the mapping is modified.

Note

Calling putenv() directly does not change os.environ, so it’s better to modify os.environ.

Note

On some platforms, including FreeBSD and Mac OS X, setting environ may cause memory leaks. Refer to the system documentation for putenv().

If putenv() is not provided, a modified copy of this mapping may be passed to the appropriate process-creation functions to cause child processes to use a modified environment.

If the platform supports the unsetenv() function, you can delete items in this mapping to unset environment variables. unsetenv() will be called automatically when an item is deleted from os.environ, and when one of the pop() or clear() methods is called.

Changed in version 2.6: Also unset environment variables when calling os.environ.clear() and os.environ.pop().

os.chdir(path)
os.fchdir(fd)
os.getcwd()

These functions are described in Files and Directories.

os.ctermid()

Return the filename corresponding to the controlling terminal of the process.

Availability: Unix.

os.getegid()

Return the effective group id of the current process. This corresponds to the “set id” bit on the file being executed in the current process.

Availability: Unix.

os.geteuid()

Return the current process’s effective user id.

Availability: Unix.

os.getgid()

Return the real group id of the current process.

Availability: Unix.

os.getgroups()

Return list of supplemental group ids associated with the current process.

Availability: Unix.

Note

On Mac OS X, getgroups() behavior differs somewhat from other Unix platforms. If the Python interpreter was built with a deployment target of 10.5 or earlier, getgroups() returns the list of effective group ids associated with the current user process; this list is limited to a system-defined number of entries, typically 16, and may be modified by calls to setgroups() if suitably privileged. If built with a deployment target greater than 10.5, getgroups() returns the current group access list for the user associated with the effective user id of the process; the group access list may change over the lifetime of the process, it is not affected by calls to setgroups(), and its length is not limited to 16. The deployment target value, MACOSX_DEPLOYMENT_TARGET, can be obtained with sysconfig.get_config_var().

os.initgroups(username, gid)

Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified group id.

Availability: Unix.

New in version 2.7.

os.getlogin()

Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use the environment variable LOGNAME to find out who the user is, or pwd.getpwuid(os.getuid())[0] to get the login name of the process’s real user id.

Availability: Unix.

os.getpgid(pid)

Return the process group id of the process with process id pid. If pid is 0, the process group id of the current process is returned.

Availability: Unix.

New in version 2.3.

os.getpgrp()

Return the id of the current process group.

Availability: Unix.

os.getpid()

Return the current process id.

Availability: Unix, Windows.

os.getppid()

Return the parent’s process id.

Availability: Unix.

os.getresuid()

Return a tuple (ruid, euid, suid) denoting the current process’s real, effective, and saved user ids.

Availability: Unix.

New in version 2.7.

os.getresgid()

Return a tuple (rgid, egid, sgid) denoting the current process’s real, effective, and saved group ids.

Availability: Unix.

New in version 2.7.

os.getuid()

Return the current process’s real user id.

Availability: Unix.

os.getenv(varname[, value])

Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to None.

Availability: most flavors of Unix, Windows.

os.putenv(varname, value)

Set the environment variable named varname to the string value. Such changes to the environment affect subprocesses started with os.system(), popen() or fork() and execv().

Availability: most flavors of Unix, Windows.

Note

On some platforms, including FreeBSD and Mac OS X, setting environ may cause memory leaks. Refer to the system documentation for putenv.

When putenv() is supported, assignments to items in os.environ are automatically translated into corresponding calls to putenv(); however, calls to putenv() don’t update os.environ, so it is actually preferable to assign to items of os.environ.

os.setegid(egid)

Set the current process’s effective group id.

Availability: Unix.

os.seteuid(euid)

Set the current process’s effective user id.

Availability: Unix.

os.setgid(gid)

Set the current process’ group id.

Availability: Unix.

os.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 identifying a group. This operation is typically available only to the superuser.

Availability: Unix.

New in version 2.2.

Note

On Mac OS X, the length of groups may not exceed the system-defined maximum number of effective group ids, typically 16. See the documentation for getgroups() for cases where it may not return the same group list set by calling setgroups().

os.setpgrp()

Call the system call setpgrp() or setpgrp(0, 0) depending on which version is implemented (if any). See the Unix manual for the semantics.

Availability: Unix.

os.setpgid(pid, pgrp)

Call the system call 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.

os.setregid(rgid, egid)

Set the current process’s real and effective group ids.

Availability: Unix.

os.setresgid(rgid, egid, sgid)

Set the current process’s real, effective, and saved group ids.

Availability: Unix.

New in version 2.7.

os.setresuid(ruid, euid, suid)

Set the current process’s real, effective, and saved user ids.

Availability: Unix.

New in version 2.7.

os.setreuid(ruid, euid)

Set the current process’s real and effective user ids.

Availability: Unix.

os.getsid(pid)

Call the system call getsid(). See the Unix manual for the semantics.

Availability: Unix.

New in version 2.4.

os.setsid()

Call the system call setsid(). See the Unix manual for the semantics.

Availability: Unix.

os.setuid(uid)

Set the current process’s user id.

Availability: Unix.

os.strerror(code)

Return the error message corresponding to the error code in code. On platforms where strerror() returns NULL when given an unknown error number, ValueError is raised.

Availability: Unix, Windows.

os.umask(mask)

Set the current numeric umask and return the previous umask.

Availability: Unix, Windows.

os.uname()

Return a 5-tuple containing information identifying the current operating system. The tuple contains 5 strings: (sysname, nodename, release, version, machine). Some systems truncate the nodename to 8 characters or to the leading component; a better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname()).

Availability: recent flavors of Unix.

os.unsetenv(varname)

Unset (delete) the environment variable named varname. Such changes to the environment affect subprocesses started with os.system(), popen() or fork() and execv().

When unsetenv() is supported, deletion of items in os.environ is automatically translated into a corresponding call to unsetenv(); however, calls to unsetenv() don’t update os.environ, so it is actually preferable to delete items of os.environ.

Availability: most flavors of Unix, Windows.

15.1.2. File Object Creation

These functions create new file objects. (See also open().)

os.fdopen(fd[, mode[, bufsize]])

Return an open file object connected to the file descriptor fd. The mode and bufsize arguments have the same meaning as the corresponding arguments to the built-in open() function. If fdopen() raises an exception, it leaves fd untouched (unclosed).

Availability: Unix, Windows.

Changed in version 2.3: When specified, the mode argument must now start with one of the letters 'r', 'w', or 'a', otherwise a ValueError is raised.

Changed in version 2.5: On Unix, when the mode argument starts with 'a', the O_APPEND flag is set on the file descriptor (which the fdopen() implementation already does on most platforms).

os.popen(command[, mode[, bufsize]])

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 open() function. The exit status of the command (encoded in the format specified for wait()) is available as the return value of the close() method of the file object, except that when the exit status is zero (termination without errors), None is returned.

Availability: Unix, Windows.

Deprecated since version 2.6: This function is obsolete. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section.

Changed in version 2.0: This function worked unreliably under Windows in earlier versions of Python. This was due to the use of the _popen() function from the libraries provided with Windows. Newer versions of Python do not use the broken implementation from the Windows libraries.

os.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 there are no file descriptors for the file.

Availability: Unix, Windows.

There are a number of different popen*() functions that provide slightly different ways to create subprocesses.

Deprecated since version 2.6: All of the popen*() functions are obsolete. Use the subprocess module.

For each of the 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 os.spawnv()). If cmd is a string it will be passed to the shell (as with 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 retrieve the return codes is to use the subprocess module; these are only available on Unix.

For a discussion of possible deadlock conditions related to the use of these functions, see Flow Control Issues.

os.popen2(cmd[, mode[, bufsize]])

Execute cmd as a sub-process and return the file objects (child_stdin, child_stdout).

Deprecated since version 2.6: This function is obsolete. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section.

Availability: Unix, Windows.

New in version 2.0.

os.popen3(cmd[, mode[, bufsize]])

Execute cmd as a sub-process and return the file objects (child_stdin, child_stdout, child_stderr).

Deprecated since version 2.6: This function is obsolete. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section.

Availability: Unix, Windows.

New in version 2.0.

os.popen4(cmd[, mode[, bufsize]])

Execute cmd as a sub-process and return the file objects (child_stdin, child_stdout_and_stderr).

Deprecated since version 2.6: This function is obsolete. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section.

Availability: Unix, Windows.

New in version 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 popen2 module using functions of the same names, but the return values of those functions have a different order.

15.1.3. File Descriptor Operations

These functions operate on I/O streams referenced using file descriptors.

File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 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.

The fileno() method can be used to obtain the file descriptor associated with a file object when required. Note that using the file descriptor directly will bypass the file object methods, ignoring aspects such as internal buffering of data.

os.close(fd)

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 os.open() or pipe(). To close a “file object” returned by the built-in function open() or by popen() or fdopen(), use its close() method.

os.closerange(fd_low, fd_high)

Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. Equivalent to:

for fd in xrange(fd_low, fd_high):
    try:
        os.close(fd)
    except OSError:
        pass

Availability: Unix, Windows.