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.

All functions accepting path or file names accept both bytes and string
objects, and result in an object of the same type, if a path or file name is
returned.

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.

In Python, file names, command line arguments, and environment variables are
represented using the string type. On some systems, decoding these strings to
and from bytes is necessary before passing them to the operating system. Python
uses the file system encoding to perform this conversion (see
sys.getfilesystemencoding()).

Changed in version 3.1: On some systems, conversion using the file system encoding may fail. In this
case, Python uses the surrogateescape encoding error handler, which means that undecodable bytes are replaced by a
Unicode character U+DCxx on decoding, and these are again translated to the
original byte on encoding.

The file system encoding must guarantee to successfully decode all bytes
below 128. If the file system encoding fails to provide this guarantee, API
functions may raise UnicodeErrors.

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.

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.

Returns the list of directories that will be searched for a named
executable, similar to a shell, when launching a process.
env, when specified, should be an environment variable dictionary
to lookup the PATH in.
By default, when env is None, environ is used.

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().

Return the name of the user logged in on the controlling terminal of the
process. For most purposes, it is more useful to use
getpass.getuser() since the latter checks the environment variables
LOGNAME or USERNAME to find out who the user is, and
falls back to pwd.getpwuid(os.getuid())[0] to get the login name of the
current real user id.

Return the parent’s process id. When the parent process has exited, on Unix
the id returned is the one of the init process (1), on Windows it is still
the same id, which may be already reused by another process.

Get program scheduling priority. The value which is one of
PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who
is interpreted relative to which (a process identifier for
PRIO_PROCESS, process group identifier for PRIO_PGRP, and a
user ID for PRIO_USER). A zero value for who denotes
(respectively) the calling process, the process group of the calling process,
or the real user ID of the calling process.

Set the environment variable named key 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.

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.

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().

Set program scheduling priority. The value which is one of
PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who
is interpreted relative to which (a process identifier for
PRIO_PROCESS, process group identifier for PRIO_PGRP, and a
user ID for PRIO_USER). A zero value for who denotes
(respectively) the calling process, the process group of the calling process,
or the real user ID of the calling process.
priority is a value in the range -20 to 19. The default priority is 0;
lower priorities cause more favorable scheduling.

Unset (delete) the environment variable named key. 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.

Return an open file object connected to the file descriptor fd. This is an
alias of the open() built-in function and accepts the same arguments.
The only difference is that the first argument of fdopen() must always
be an integer.

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.

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.

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. See
chown(). As of Python 3.3, this is equivalent to os.chown(fd,uid,gid).

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.

If name is a string and is not known, 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 OSError is raised with
errno.EINVAL for the error number.

Apply, test or remove a POSIX lock on an open file descriptor.
fd is an open file descriptor.
cmd specifies the command to use - one of F_LOCK, F_TLOCK,
F_ULOCK or F_TEST.
len specifies the section of the file to lock.

Set the current position of file descriptor fd to position pos, modified
by how: SEEK_SET or 0 to set the position relative to the
beginning of the file; SEEK_CUR or 1 to set it relative to the
current position; SEEK_END or 2 to set it relative to the end of
the file. Return the new cursor position in bytes, starting from the beginning.

Open the file path and set various flags according to flags and possibly
its mode according to mode. When computing mode, the current umask value
is first masked out. Return the file descriptor for the newly opened file.
The new file descriptor is non-inheritable.

For a description of the flag and mode values, see the C run-time documentation;
flag constants (like O_RDONLY and O_WRONLY) are defined in
the os module. In particular, on Windows adding
O_BINARY is needed to open files in binary mode.

Changed in version 3.4: The new file descriptor is now non-inheritable.

Note

This function is intended for low-level I/O. For normal usage, use the
built-in function open(), which returns a file object with
read() and write() methods (and many more). To
wrap a file descriptor in a file object, use fdopen().

New in version 3.3: The dir_fd argument.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an
exception, the function now retries the system call instead of raising an
InterruptedError exception (see PEP 475 for the rationale).

The following constants are options for the flags parameter to the
open() function. They can be combined using the bitwise OR operator
|. Some of them are not available on all platforms. For descriptions of
their availability and use, consult the open(2) manual page on Unix
or the MSDN on Windows.

Open a new pseudo-terminal pair. Return a pair of file descriptors
(master,slave) for the pty and the tty, respectively. The new file
descriptors are non-inheritable. For a (slightly) more
portable approach, use the pty module.

Availability: some flavors of Unix.

Changed in version 3.4: The new file descriptors are now non-inheritable.

Create a pipe with flags set atomically.
flags can be constructed by ORing together one or more of these values:
O_NONBLOCK, O_CLOEXEC.
Return a pair of file descriptors (r,w) usable for reading and writing,
respectively.

Read at most n bytes from file descriptor fd. Return a bytestring containing the
bytes read. If the end of the file referred to by fd has been reached, an
empty bytes object is returned.

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 read a
“file object” returned by the built-in function open() or by
popen() or fdopen(), or sys.stdin, use its
read() or readline() methods.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an
exception, the function now retries the system call instead of raising an
InterruptedError exception (see PEP 475 for the rationale).

Copy count bytes from file descriptor in to file descriptor out
starting at offset.
Return the number of bytes sent. When EOF is reached return 0.

The first function notation is supported by all platforms that define
sendfile().

On Linux, if offset is given as None, the bytes are read from the
current position of in and the position of in is updated.

The second case may be used on Mac OS X and FreeBSD where headers and
trailers are arbitrary sequences of buffers that are written before and
after the data from in is written. It returns the same as the first case.

On Mac OS X and FreeBSD, a value of 0 for count specifies to send until
the end of in is reached.

All platforms support sockets as out file descriptor, and some platforms
allow other types (e.g. regular file, pipe) as well.

Cross-platform applications should not use headers, trailers and flags
arguments.

Read from a file descriptor fd into a number of mutable bytes-like
objectsbuffers. readv() will transfer data
into each buffer until it is full and then move on to the next buffer in the
sequence to hold the rest of the data. readv() returns the total
number of bytes read (which may be less than the total capacity of all the
objects).

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an
exception, the function now retries the system call instead of raising an
InterruptedError exception (see PEP 475 for the rationale).

Write the contents of buffers to file descriptor fd. buffers must be a
sequence of bytes-like objects. Buffers are
processed in array order. Entire contents of first buffer is written before
proceeding to second, and so on. The operating system may set a limit
(sysconf() value SC_IOV_MAX) on the number of buffers that can be used.

writev() writes the contents of each object to the file descriptor
and returns the total number of bytes written.

A file descriptor has an “inheritable” flag which indicates if the file descriptor
can be inherited by child processes. Since Python 3.4, file descriptors
created by Python are non-inheritable by default.

On UNIX, non-inheritable file descriptors are closed in child processes at the
execution of a new program, other file descriptors are inherited.

On Windows, non-inheritable handles and file descriptors are closed in child
processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout
and stderr), which are always inherited. Using spawn* functions,
all inheritable handles and all inheritable file descriptors are inherited.
Using the subprocess module, all file descriptors except standard
streams are closed, and inheritable handles are only inherited if the
close_fds parameter is False.

On some Unix platforms, many of these functions support one or more of these
features:

specifying a file descriptor:
For some functions, the path argument can be not only a string giving a path
name, but also a file descriptor. The function will then operate on the file
referred to by the descriptor. (For POSIX systems, Python will call the
f... version of the function.)

You can check whether or not path can be specified as a file descriptor on
your platform using os.supports_fd. If it is unavailable, using it
will raise a NotImplementedError.

If the function also supports dir_fd or follow_symlinks arguments, it is
an error to specify one of those when supplying path as a file descriptor.

paths relative to directory descriptors: If dir_fd is not None, it
should be a file descriptor referring to a directory, and the path to operate
on should be relative; path will then be relative to that directory. If the
path is absolute, dir_fd is ignored. (For POSIX systems, Python will call
the ...at or f...at version of the function.)

not following symlinks: If follow_symlinks is
False, and the last element of the path to operate on is a symbolic link,
the function will operate on the symbolic link itself instead of the file the
link points to. (For POSIX systems, Python will call the l... version of
the function.)

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 F_OK to test the existence of path, or it
can be the inclusive OR of one or more of R_OK, W_OK, and
X_OK to test permissions. Return True if access is allowed,
False if not. See the Unix man page access(2) for more
information.

If effective_ids is True, access() will perform its access
checks using the effective uid/gid instead of the real uid/gid.
effective_ids may not be supported on your platform; you can check whether
or not it is available using os.supports_effective_ids. If it is
unavailable, using it will raise a NotImplementedError.

Note

Using access() to check if a user is authorized to e.g. open a file
before actually doing so using open() creates a security hole,
because the user might exploit the short time interval between checking
and opening the file to manipulate it. It’s preferable to use EAFP
techniques. For example:

I/O operations may fail even when access() indicates that they would
succeed, particularly for operations on network filesystems which may have
permissions semantics beyond the usual POSIX permission-bit model.

Changed in version 3.3: Added the dir_fd, effective_ids, and follow_symlinks parameters.

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. As of Python 3.3, this is equivalent to os.chdir(fd).

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 chmod()
for possible values of mode. As of Python 3.3, this is equivalent to
os.chmod(path,mode,follow_symlinks=False).

Return a list containing the names of the entries in the directory given by
path. The list is in arbitrary order, and does not include the special
entries '.' and '..' even if they are present in the directory.

path may be a path-like object. If path is of type bytes
(directly or indirectly through the PathLike interface),
the filenames returned will also be of type bytes;
in all other circumstances, they will be of type str.

On some systems, mode is ignored. Where it is used, the current umask
value is first masked out. If bits other than the last 9 (i.e. the last 3
digits of the octal representation of the mode) are set, their meaning is
platform-dependent. On some platforms, they are ignored and you should call
chmod() explicitly to set them.

If exist_ok is False (the default), an OSError is raised if the
target directory already exists.

Note

makedirs() will become confused if the path elements to create
include pardir (eg. “..” on UNIX systems).

This function handles UNC paths correctly.

New in version 3.2: The exist_ok parameter.

Changed in version 3.4.1: Before Python 3.4.1, if exist_ok was True and the directory existed,
makedirs() would still raise an error if mode did not match the
mode of the existing directory. Since this behavior was impossible to
implement safely, it was removed in Python 3.4.1. See bpo-21082.

FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
are deleted (for example with 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 mkfifo()
doesn’t open the FIFO — it just creates the rendezvous point.

Create a filesystem node (file, device special file or named pipe) named
path. mode specifies both the permissions to use and the type of node
to be created, being combined (bitwise OR) with one of stat.S_IFREG,
stat.S_IFCHR, stat.S_IFBLK, and stat.S_IFIFO (those constants are
available in stat). For stat.S_IFCHR and stat.S_IFBLK,
device defines the newly created device special file (probably using
os.makedev()), otherwise it is ignored.

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.

If name is a string and is not known, 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 OSError is raised with
errno.EINVAL for the error number.

Dictionary mapping names accepted by pathconf() and 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.

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),result).

If the path is a string object (directly or indirectly through a
PathLike interface), the result will also be a string object,
and the call may raise a UnicodeDecodeError. If the path is a bytes
object (direct or indirectly), the result will be a bytes object.

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 until the original file is no longer in use.

Remove directories recursively. Works like rmdir() except that, if the
leaf directory is successfully removed, 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 OSError if the leaf directory could not be
successfully removed.

Rename the file or directory src to dst. If dst is a directory,
OSError will be raised. On Unix, if dst exists and is a file, it will
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, OSError will be raised even if it is a
file.

Recursive directory or file renaming function. Works like 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 removedirs().

Note

This function can fail with the new directory structure made if you lack
permissions needed to remove the leaf directory or file.

Rename the file or directory src to dst. If dst is a directory,
OSError will be raised. If dst exists and is a file, it will
be replaced silently if the user has permission. The operation may fail
if src and dst are on different filesystems. If successful,
the renaming will be an atomic operation (this is a POSIX requirement).

Return an iterator of os.DirEntry objects corresponding to the
entries in the directory given by path. The entries are yielded in
arbitrary order, and the special entries '.' and '..' are not
included.

Using scandir() instead of listdir() can significantly
increase the performance of code that also needs file type or file
attribute information, because os.DirEntry objects expose this
information if the operating system provides it when scanning a directory.
All os.DirEntry methods may perform a system call, but
is_dir() and is_file() usually only
require a system call for symbolic links; os.DirEntry.stat()
always requires a system call on Unix but only requires one for
symbolic links on Windows.

path may be a path-like object. If path is of type bytes
(directly or indirectly through the PathLike interface),
the type of the name and path
attributes of each os.DirEntry will be bytes; in all other
circumstances, they will be of type str.

This is called automatically when the iterator is exhausted or garbage
collected, or when an error happens during iterating. However it
is advisable to call it explicitly or use the with
statement.

New in version 3.6.

The following example shows a simple use of scandir() to display all
the files (excluding directories) in the given path that don’t start with
'.'. The entry.is_file() call will generally not make an additional
system call:

Object yielded by scandir() to expose the file path and other file
attributes of a directory entry.

scandir() will provide as much of this information as possible without
making additional system calls. When a stat() or lstat() system call
is made, the os.DirEntry object will cache the result.

os.DirEntry instances are not intended to be stored in long-lived data
structures; if you know the file metadata has changed or if a long time has
elapsed since calling scandir(), call os.stat(entry.path) to fetch
up-to-date information.

Because the os.DirEntry methods can make operating system calls, they may
also raise OSError. If you need very fine-grained
control over errors, you can catch OSError when calling one of the
os.DirEntry methods and handle as appropriate.

Return True if this entry is a directory or a symbolic link pointing
to a directory; return False if the entry is or points to any other
kind of file, or if it doesn’t exist anymore.

If follow_symlinks is False, return True only if this entry
is a directory (without following symlinks); return False if the
entry is any other kind of file or if it doesn’t exist anymore.

The result is cached on the os.DirEntry object, with a separate cache
for follow_symlinksTrue and False. Call os.stat() along
with stat.S_ISDIR() to fetch up-to-date information.

On the first, uncached call, no system call is required in most cases.
Specifically, for non-symlinks, neither Windows or Unix require a system
call, except on certain Unix file systems, such as network file systems,
that return dirent.d_type==DT_UNKNOWN. If the entry is a symlink,
a system call will be required to follow the symlink unless
follow_symlinks is False.

Return True if this entry is a symbolic link (even if broken);
return False if the entry points to a directory or any kind of file,
or if it doesn’t exist anymore.

The result is cached on the os.DirEntry object. Call
os.path.islink() to fetch up-to-date information.

On the first, uncached call, no system call is required in most cases.
Specifically, neither Windows or Unix require a system call, except on
certain Unix file systems, such as network file systems, that return
dirent.d_type==DT_UNKNOWN.

Return a stat_result object for this entry. This method
follows symbolic links by default; to stat a symbolic link add the
follow_symlinks=False argument.

On Unix, this method always requires a system call. On Windows, it
only requires a system call if follow_symlinks is True and the
entry is a symbolic link.

On Windows, the st_ino, st_dev and st_nlink attributes of the
stat_result are always set to zero. Call os.stat() to
get these attributes.

The result is cached on the os.DirEntry object, with a separate cache
for follow_symlinksTrue and False. Call os.stat() to
fetch up-to-date information.

Note that there is a nice correspondence between several attributes
and methods of os.DirEntry and of pathlib.Path. In
particular, the name attribute has the same
meaning, as do the is_dir(), is_file(), is_symlink()
and stat() methods.

New in version 3.5.

Changed in version 3.6: Added support for the PathLike interface. Added support
for bytes paths on Windows.

Get the status of a file or a file descriptor. Perform the equivalent of a
stat() system call on the given path. path may be specified as
either a string or bytes – directly or indirectly through the PathLike
interface – or as an open file descriptor. Return a stat_result
object.

This function normally follows symlinks; to stat a symlink add the argument
follow_symlinks=False, or use lstat().

The exact meaning and resolution of the st_atime,
st_mtime, and st_ctime attributes depend on the operating
system and the file system. For example, on Windows systems using the FAT
or FAT32 file systems, st_mtime has 2-second resolution, and
st_atime has only 1-day resolution. See your operating system
documentation for details.

Determine whether stat_result represents time stamps as float objects.
If newvalue is True, future calls to stat() return floats, if it is
False, future calls return ints. If newvalue is omitted, return the
current setting.

Python now returns float values by default. Applications which do not work
correctly with floating point time stamps can use this function to restore the
old behaviour.

The resolution of the timestamps (that is the smallest possible fraction)
depends on the system. Some systems only support second resolution; on these
systems, the fraction will always be zero.

It is recommended that this setting is only changed at program startup time in
the __main__ module; libraries should never change this setting. If an
application uses a library that works incorrectly if floating point time stamps
are processed, this application should turn the feature off until the library
has been corrected.

Perform a statvfs() system call on the given path. The return value is
an object whose attributes describe the filesystem on the given path, and
correspond to the members of the statvfs structure, namely:
f_bsize, f_frsize, f_blocks, f_bfree,
f_bavail, f_files, f_ffree, f_favail,
f_flag, f_namemax.

Two module-level constants are defined for the f_flag attribute’s
bit-flags: if ST_RDONLY is set, the filesystem is mounted
read-only, and if ST_NOSUID is set, the semantics of
setuid/setgid bits are disabled or not supported.

A Set object indicating which functions in the
os module permit use of their dir_fd parameter. Different platforms
provide different functionality, and an option that might work on one might
be unsupported on another. For consistency’s sakes, functions that support
dir_fd always allow specifying the parameter, but will raise an exception
if the functionality is not actually available.

To check whether a particular function permits use of its dir_fd
parameter, use the in operator on supports_dir_fd. As an example,
this expression determines whether the dir_fd parameter of os.stat()
is locally available:

os.statinos.supports_dir_fd

Currently dir_fd parameters only work on Unix platforms; none of them work
on Windows.

A Set object indicating which functions in the
os module permit use of the effective_ids parameter for
os.access(). If the local platform supports it, the collection will
contain os.access(), otherwise it will be empty.

To check whether you can use the effective_ids parameter for
os.access(), use the in operator on supports_effective_ids,
like so:

os.accessinos.supports_effective_ids

Currently effective_ids only works on Unix platforms; it does not work on
Windows.

A Set object indicating which functions in the
os module permit specifying their path parameter as an open file
descriptor. Different platforms provide different functionality, and an
option that might work on one might be unsupported on another. For
consistency’s sakes, functions that support fd always allow specifying
the parameter, but will raise an exception if the functionality is not
actually available.

To check whether a particular function permits specifying an open file
descriptor for its path parameter, use the in operator on
supports_fd. As an example, this expression determines whether
os.chdir() accepts open file descriptors when called on your local
platform:

A Set object indicating which functions in the
os module permit use of their follow_symlinks parameter. Different
platforms provide different functionality, and an option that might work on
one might be unsupported on another. For consistency’s sakes, functions that
support follow_symlinks always allow specifying the parameter, but will
raise an exception if the functionality is not actually available.

To check whether a particular function permits use of its follow_symlinks
parameter, use the in operator on supports_follow_symlinks. As an
example, this expression determines whether the follow_symlinks parameter
of os.stat() is locally available:

On Windows, a symlink represents either a file or a directory, and does not
morph to the target dynamically. If the target is present, the type of the
symlink will be created to match. Otherwise, the symlink will be created
as a directory if target_is_directory is True or a file symlink (the
default) otherwise. On non-Window platforms, target_is_directory is ignored.

Symbolic link support was introduced in Windows 6.0 (Vista). symlink()
will raise a NotImplementedError on Windows versions earlier than 6.0.

On Windows, the SeCreateSymbolicLinkPrivilege is required in order to
successfully create symlinks. This privilege is not typically granted to
regular users but is available to accounts which can escalate privileges
to the administrator level. Either obtaining the privilege or running your
application as an administrator are ways to successfully create symlinks.

OSError is raised when the function is called by an unprivileged
user.

Availability: Unix, Windows.

Changed in version 3.2: Added support for Windows 6.0 (Vista) symbolic links.

New in version 3.3: Added the dir_fd argument, and now allow target_is_directory
on non-Windows platforms.

utime() takes two optional parameters, times and ns.
These specify the times set on path and are used as follows:

If ns is specified,
it must be a 2-tuple of the form (atime_ns,mtime_ns)
where each member is an int expressing nanoseconds.

If times is not None,
it must be a 2-tuple of the form (atime,mtime)
where each member is an int or float expressing seconds.

If times is None and ns is unspecified,
this is equivalent to specifying ns=(atime_ns,mtime_ns)
where both times are the current time.

It is an error to specify tuples for both times and ns.

Whether a directory can be given for path
depends on whether the operating system implements directories as files
(for example, Windows does not). Note that the exact times you set here may
not be returned by a subsequent stat() call, depending on the
resolution with which your operating system records access and modification
times; see stat(). The best way to preserve exact times is to
use the st_atime_ns and st_mtime_ns fields from the os.stat()
result object with the ns parameter to utime.

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
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).

If optional argument topdown is True or not specified, the triple for a
directory is generated before the triples for any of its subdirectories
(directories are generated top-down). If topdown is False, the triple
for a directory is generated after the triples for all of its subdirectories
(directories are generated bottom-up). No matter the value of topdown, the
list of subdirectories is retrieved before the tuples for the directory and
its subdirectories are generated.

When topdown is True, the caller can modify the dirnames list in-place
(perhaps using del or slice assignment), and 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
walk() about directories the caller creates or renames before it resumes
walk() again. Modifying dirnames when topdown is False has
no effect on the behavior of the walk, because in bottom-up mode the directories
in dirnames are generated before dirpath itself is generated.

By default, errors from the listdir() call are ignored. If optional
argument onerror is specified, it should be a function; it will be called with
one argument, an 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.

By default, 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.

Note

Be aware that setting followlinks to True can lead to infinite
recursion if a link points to a parent directory of itself. 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 walk(). walk() never changes the current
directory, and assumes that its caller doesn’t either.

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:

In the next example (simple implementation of shutil.rmtree()),
walking the tree bottom-up is essential, rmdir() doesn’t allow
deleting a directory before the directory is empty:

# 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.importosforroot,dirs,filesinos.walk(top,topdown=False):fornameinfiles:os.remove(os.path.join(root,name))fornameindirs:os.rmdir(os.path.join(root,name))

In the next example, walking the tree bottom-up is essential:
rmdir() doesn’t allow deleting a directory before the directory is
empty:

# 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.importosforroot,dirs,files,rootfdinos.fwalk(top,topdown=False):fornameinfiles:os.unlink(name,dir_fd=rootfd)fornameindirs:os.rmdir(name,dir_fd=rootfd)

Return the value of the extended filesystem attribute attribute for
path. attribute can be bytes or str (directly or indirectly through the
PathLike interface). If it is str, it is encoded with the filesystem
encoding.

Return a list of the extended filesystem attributes on path. The
attributes in the list are represented as strings decoded with the filesystem
encoding. If path is None, listxattr() will examine the current
directory.

Removes the extended filesystem attribute attribute from path.
attribute should be bytes or str (directly or indirectly through the
PathLike interface). If it is a string, it is encoded
with the filesystem encoding.

Set the extended filesystem attribute attribute on path to value.
attribute must be a bytes or str with no embedded NULs (directly or
indirectly through the PathLike interface). If it is a str,
it is encoded with the filesystem encoding. flags may be
XATTR_REPLACE or XATTR_CREATE. If XATTR_REPLACE is
given and the attribute does not exist, EEXISTS will be raised.
If XATTR_CREATE is given and the attribute already exists, the
attribute will not be created and ENODATA will be raised.

The various exec* functions take a list of arguments for the new
program loaded into the process. In each case, the first of these arguments is
passed to the new program as its own name rather than as an argument a user may
have typed on a command line. For the C programmer, this is the argv[0]
passed to a program’s main(). For example, os.execv('/bin/echo',['foo','bar']) will only print bar on standard output; foo will seem
to be ignored.

Generate a 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 calling this function will not call the
Python signal handler registered for SIGABRT with
signal.signal().

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,
and will have the same process id as the caller. Errors will be reported as
OSError exceptions.

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
sys.stdout.flush() or os.fsync() before calling an
exec* function.

The “l” and “v” variants of the exec* functions differ in how
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 execl*()
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.

The variants which include a “p” near the end (execlp(),
execlpe(), execvp(), and execvpe()) will use the
PATH environment variable to locate the program file. When the
environment is being replaced (using one of the exec*e variants,
discussed in the next paragraph), the new environment is used as the source of
the PATH variable. The other variants, execl(), execle(),
execv(), and execve(), will not use the PATH variable to
locate the executable; path must contain an appropriate absolute or relative
path.

For execle(), execlpe(), execve(), and execvpe() (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 (these are used
instead of the current process’ environment); the functions execl(),
execlp(), execv(), and execvp() all cause the new process to
inherit the environment of the current process.

For execve() on some platforms, path may also be specified as an open
file descriptor. This functionality may not be supported on your platform;
you can check whether or not it is available using os.supports_fd.
If it is unavailable, using it will raise a NotImplementedError.

Availability: Unix, Windows.

New in version 3.3: Added support for specifying an open file descriptor for path
for execve().

The standard way to exit is sys.exit(n). _exit() should
normally only be used in the child process after a fork().

The following exit codes are defined and can be used with _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.

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
pty module. If an error occurs OSError is raised.

Send signal sig to the process pid. Constants for the specific signals
available on the host platform are defined in the signal module.

Windows: The signal.CTRL_C_EVENT and
signal.CTRL_BREAK_EVENT signals are special signals which can
only be sent to console processes which share a common console window,
e.g., some subprocesses. Any other value for sig will cause the process
to be unconditionally killed by the TerminateProcess API, and the exit code
will be set to sig. The Windows version of kill() additionally takes
process handles to be killed.

Open a pipe to or from command cmd.
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 buffering argument has the same meaning as
the corresponding argument to the built-in open() function. The
returned file object reads or writes text strings rather than bytes.

The close method returns None if the subprocess exited
successfully, or the subprocess’s return code if there was an
error. On POSIX systems, if the return code is positive it
represents the return value of the process left-shifted by one
byte. If the return code is negative, the process was terminated
by the signal given by the negated value of the return code. (For
example, the return value might be -signal.SIGKILL if the
subprocess was killed.) On Windows systems, the return value
contains the signed integer return code from the child process.

This is implemented using subprocess.Popen; see that class’s
documentation for more powerful ways to manage and communicate with
subprocesses.

If mode is P_NOWAIT, this function returns the process id of the new
process; if mode is 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
be used with the waitpid() function.

The “l” and “v” variants of the spawn* functions differ in how
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
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.

The variants which include a second “p” near the end (spawnlp(),
spawnlpe(), spawnvp(), and spawnvpe()) will use the
PATH environment variable to locate the program file. When the
environment is being replaced (using one of the spawn*e variants,
discussed in the next paragraph), the new environment is used as the source of
the PATH variable. The other variants, spawnl(),
spawnle(), spawnv(), and spawnve(), will not use the
PATH variable to locate the executable; path must contain an
appropriate absolute or relative path.

For spawnle(), spawnlpe(), spawnve(), and spawnvpe()
(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 (they are
used instead of the current process’ environment); the functions
spawnl(), spawnlp(), spawnv(), and spawnvp() all cause
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.

Possible values for the mode parameter to the spawn* family of
functions. If either of these values is given, the spawn*() functions
will return as soon as the new process has been created, with the process id as
the return value.

Possible value for the mode parameter to the spawn* family of
functions. If this is given as mode, the spawn*() functions will not
return until the new process has run to completion and will return the exit code
of the process the run is successful, or -signal if a signal kills the
process.

Possible values for the mode parameter to the spawn* family of
functions. These are less portable than those listed above. P_DETACH
is similar to P_NOWAIT, but the new process is detached from the
console of the calling process. If P_OVERLAY is used, the current
process will be replaced; the spawn* function will not return.

When operation is not specified or 'open', this acts like double-clicking
the file in Windows Explorer, or giving the file name as an argument to the
start command from the interactive command shell: the file is opened
with whatever application (if any) its extension is associated.

When another operation is given, it must be a “command verb” that specifies
what should be done with the file. Common verbs documented by Microsoft are
'print' and 'edit' (to be used on files) as well as 'explore' and
'find' (to be used on directories).

startfile() returns as soon as the associated application is launched.
There is no option to wait for the application to close, and no way to retrieve
the application’s exit status. The path parameter is relative to the current
directory. If you want to use an absolute path, make sure the first character
is not a slash ('/'); the underlying Win32 ShellExecute() function
doesn’t work if it is. Use the os.path.normpath() function to ensure that
the path is properly encoded for Win32.

To reduce interpreter startup overhead, the Win32 ShellExecute()
function is not resolved until this function is first called. If the function
cannot be resolved, NotImplementedError will be raised.

Execute the command (a string) in a subshell. This is implemented by calling
the Standard C function system(), and has the same limitations.
Changes to sys.stdin, etc. are not reflected in the environment of
the executed command. If command generates any output, it will be sent to
the interpreter standard output stream.

On Unix, the return value is the exit status of the process encoded in the
format specified for wait(). Note that POSIX does not specify the
meaning of the return value of the C 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. The shell is given by the Windows environment variable
COMSPEC: it is usually cmd.exe, which returns the exit
status of the command run; on systems using a non-native shell, consult your
shell documentation.

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
produced.

Wait for the completion of one or more child processes.
idtype can be P_PID, P_PGID or P_ALL.
id specifies the pid to wait on.
options is constructed from the ORing of one or more of WEXITED,
WSTOPPED or WCONTINUED and additionally may be ORed with
WNOHANG or WNOWAIT. The return value is an object
representing the data contained in the siginfo_t structure, namely:
si_pid, si_uid, si_signo, si_status,
si_code or None if WNOHANG is specified and there are no
children in a waitable state.

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
for wait()). The semantics of the call are affected by the value of the
integer options, which should be 0 for normal operation.

If pid is greater than 0, waitpid() requests status information for
that specific process. If pid is 0, the request is for the status of any
child in the process group of the current process. If pid is -1, the
request pertains to any child of the current process. If pid is less than
-1, status is requested for any process in the process group -pid (the
absolute value of pid).

An OSError is raised with the value of errno when the syscall
returns -1.

On Windows: Wait for completion of a process given by process handle pid, and
return a tuple containing pid, and its exit status shifted left by 8 bits
(shifting makes cross-platform use of the function easier). A pid less than or
equal to 0 has no special meaning on Windows, and raises an exception. The
value of integer options has no effect. pid can refer to any process whose
id is known, not necessarily a child process. The spawn*
functions called with P_NOWAIT return suitable process handles.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an
exception, the function now retries the system call instead of raising an
InterruptedError exception (see PEP 475 for the rationale).

Similar to waitpid(), except no process id argument is given and a
3-element tuple containing the child’s process id, exit status indication, and
resource usage information is returned. Refer to resource.getrusage() for details on resource usage information. The
option argument is the same as that provided to waitpid() and
wait4().

Similar to waitpid(), except a 3-element tuple, containing the child’s
process id, exit status indication, and resource usage information is returned.
Refer to resource.getrusage() for details on
resource usage information. The arguments to wait4() are the same
as those provided to waitpid().

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.

If the configuration value specified by name isn’t defined, None is
returned.

If name is a string and is not known, 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 OSError is raised with
errno.EINVAL for the error number.

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 confstr() apply here as well; the dictionary that
provides information on the known names is given by sysconf_names.

The character used by the operating system to separate pathname components.
This is '/' for POSIX and '\\' for Windows. Note that knowing this
is not sufficient to be able to parse or concatenate pathnames — use
os.path.split() and os.path.join() — but it is occasionally
useful. Also available via os.path.

An alternative character used by the operating system to separate pathname
components, or None if only one separator character exists. This is set to
'/' on Windows systems where sep is a backslash. Also available via
os.path.

The string used to separate (or, rather, terminate) lines on the current
platform. This may be a single character, such as '\n' for POSIX, or
multiple characters, for example, '\r\n' for Windows. Do not use
os.linesep as a line terminator when writing files opened in text mode (the
default); use a single '\n' instead, on all platforms.

Get up to size random bytes. The function can return less bytes than
requested.

These bytes can be used to seed user-space random number generators or for
cryptographic purposes.

getrandom() relies on entropy gathered from device drivers and other
sources of environmental noise. Unnecessarily reading large quantities of
data will have a negative impact on other users of the /dev/random and
/dev/urandom devices.

The flags argument is a bit mask that can contain zero or more of the
following values ORed together: os.GRND_RANDOM and
GRND_NONBLOCK.

This function returns random bytes from an OS-specific randomness source. The
returned data should be unpredictable enough for cryptographic applications,
though its exact quality depends on the OS implementation.

On Linux, if the getrandom() syscall is available, it is used in
blocking mode: block until the system urandom entropy pool is initialized
(128 bits of entropy are collected by the kernel). See the PEP 524 for
the rationale. On Linux, the getrandom() function can be used to get
random bytes in non-blocking mode (using the GRND_NONBLOCK flag) or
to poll until the system urandom entropy pool is initialized.

On a Unix-like system, random bytes are read from the /dev/urandom
device. If the /dev/urandom device is not available or not readable, the
NotImplementedError exception is raised.

On Windows, it will use CryptGenRandom().

See also

The secrets module provides higher level functions. For an
easy-to-use interface to the random number generator provided by your
platform, please see random.SystemRandom.

Changed in version 3.6.0: On Linux, getrandom() is now used in blocking mode to increase the
security.

Changed in version 3.5.2: On Linux, if the getrandom() syscall blocks (the urandom entropy pool
is not initialized yet), fall back on reading /dev/urandom.

Changed in version 3.5: On Linux 3.17 and newer, the getrandom() syscall is now used
when available. On OpenBSD 5.6 and newer, the C getentropy()
function is now used. These functions avoid the usage of an internal file
descriptor.