os — Miscellaneous operating system interfaces

Source code:Lib/os.py


This module provides a portable way of using operating system dependentfunctionality. If you just want to read or write a file seeopen(), ifyou want to manipulate paths, see theos.path module, and if you want toread all the lines in all the files on the command line see thefileinputmodule. For creating temporary files and directories see thetempfilemodule, and for high-level file and directory handling see theshutilmodule.

Notes on the availability of these functions:

  • The design of all built-in operating system dependent modules of Python issuch that as long as the same functionality is available, it uses the sameinterface; for example, the functionos.stat(path) returns statinformation aboutpath in the same format (which happens to have originatedwith the POSIX interface).

  • Extensions peculiar to a particular operating system are also availablethrough theos module, but using them is of course a threat toportability.

  • All functions accepting path or file names accept both bytes and stringobjects, and result in an object of the same type, if a path or file name isreturned.

  • On VxWorks, os.fork, os.execv and os.spawn*p* are not supported.

Note

All functions in this module raiseOSError (or subclasses thereof) inthe case of invalid or inaccessible file names and paths, or other argumentsthat have the correct type, but are not accepted by the operating system.

exceptionos.error

An alias for the built-inOSError exception.

os.name

The name of the operating system dependent module imported. The followingnames have currently been registered:'posix','nt','java'.

See also

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

Theplatform module provides detailed checks for thesystem’s identity.

File Names, Command Line Arguments, and Environment Variables

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

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

The file system encoding must guarantee to successfully decode all bytesbelow 128. If the file system encoding fails to provide this guarantee, APIfunctions may raise UnicodeErrors.

Process Parameters

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

os.ctermid()

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

Availability: Unix.

os.environ

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

This mapping is captured the first time theos module is imported,typically during Python startup as part of processingsite.py. Changesto the environment made after this time are not reflected inos.environ,except for changes made by modifyingos.environ directly.

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

On Unix, keys and values usesys.getfilesystemencoding() and'surrogateescape' error handler. Useenvironb if you would liketo use a different encoding.

Note

Callingputenv() directly does not changeos.environ, so it’s betterto modifyos.environ.

Note

On some platforms, including FreeBSD and Mac OS X, settingenviron maycause memory leaks. Refer to the system documentation forputenv().

Ifputenv() is not provided, a modified copy of this mapping may bepassed to the appropriate process-creation functions to cause child processesto use a modified environment.

If the platform supports theunsetenv() function, you can delete items inthis mapping to unset environment variables.unsetenv() will be calledautomatically when an item is deleted fromos.environ, and whenone of thepop() orclear() methods is called.

os.environb

Bytes version ofenviron: amapping object representing theenvironment as byte strings.environ andenvironb aresynchronized (modifyenvironb updatesenviron, and viceversa).

environb is only available ifsupports_bytes_environ isTrue.

New in version 3.2.

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

These functions are described inFiles and Directories.

os.fsencode(filename)

Encodepath-likefilename to the filesystemencoding with'surrogateescape' error handler, or'strict' onWindows; returnbytes unchanged.

fsdecode() is the reverse function.

New in version 3.2.

Changed in version 3.6:Support added to accept objects implementing theos.PathLikeinterface.

os.fsdecode(filename)

Decode thepath-likefilename from thefilesystem encoding with'surrogateescape' error handler, or'strict'on Windows; returnstr unchanged.

fsencode() is the reverse function.

New in version 3.2.

Changed in version 3.6:Support added to accept objects implementing theos.PathLikeinterface.

os.fspath(path)

Return the file system representation of the path.

Ifstr orbytes is passed in, it is returned unchanged.Otherwise__fspath__() is called and its value isreturned as long as it is astr orbytes object.In all other cases,TypeError is raised.

New in version 3.6.

classos.PathLike

Anabstract base class for objects representing a file system path,e.g.pathlib.PurePath.

New in version 3.6.

abstractmethod__fspath__()

Return the file system path representation of the object.

The method should only return astr orbytes object,with the preference being forstr.

os.getenv(key,default=None)

Return the value of the environment variablekey if it exists, ordefault if it doesn’t.key,default and the result are str.

On Unix, keys and values are decoded withsys.getfilesystemencoding()and'surrogateescape' error handler. Useos.getenvb() if youwould like to use a different encoding.

Availability: most flavors of Unix, Windows.

os.getenvb(key,default=None)

Return the value of the environment variablekey if it exists, ordefault if it doesn’t.key,default and the result are bytes.

getenvb() is only available ifsupports_bytes_environisTrue.

Availability: most flavors of Unix.

New in version 3.2.

os.get_exec_path(env=None)

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

New in version 3.2.

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.getgrouplist(user,group)

Return list of group ids thatuser belongs to. Ifgroup is not in thelist, it is included; typically,group is specified as the group IDfield from the password record foruser.

Availability: Unix.

New in version 3.3.

os.getgroups()

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

Availability: Unix.

Note

On Mac OS X,getgroups() behavior differs somewhat fromother Unix platforms. If the Python interpreter was built with adeployment target of10.5 or earlier,getgroups() returnsthe 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 tosetgroups() if suitably privileged.If built with a deployment target greater than10.5,getgroups() returns the current group access list for the userassociated with the effective user id of the process; the group accesslist may change over the lifetime of the process, it is not affected bycalls tosetgroups(), and its length is not limited to 16. Thedeployment target value,MACOSX_DEPLOYMENT_TARGET, can beobtained withsysconfig.get_config_var().

os.getlogin()

Return the name of the user logged in on the controlling terminal of theprocess. For most purposes, it is more useful to usegetpass.getuser() since the latter checks the environment variablesLOGNAME orUSERNAME to find out who the user is, andfalls back topwd.getpwuid(os.getuid())[0] to get the login name of thecurrent real user id.

Availability: Unix, Windows.

os.getpgid(pid)

Return the process group id of the process with process idpid. Ifpid is 0,the process group id of the current process is returned.

Availability: Unix.

os.getpgrp()

Return the id of the current process group.

Availability: Unix.

os.getpid()

Return the current process id.

os.getppid()

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

Availability: Unix, Windows.

Changed in version 3.2:Added support for Windows.

os.getpriority(which,who)

Get program scheduling priority. The valuewhich is one ofPRIO_PROCESS,PRIO_PGRP, orPRIO_USER, andwhois interpreted relative towhich (a process identifier forPRIO_PROCESS, process group identifier forPRIO_PGRP, and auser ID forPRIO_USER). A zero value forwho denotes(respectively) the calling process, the process group of the calling process,or the real user ID of the calling process.

Availability: Unix.

New in version 3.3.

os.PRIO_PROCESS
os.PRIO_PGRP
os.PRIO_USER

Parameters for thegetpriority() andsetpriority() functions.

Availability: Unix.

New in version 3.3.

os.getresuid()

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

Availability: Unix.

New in version 3.2.

os.getresgid()

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

Availability: Unix.

New in version 3.2.

os.getuid()

Return the current process’s real user id.

Availability: Unix.

os.initgroups(username,gid)

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

Availability: Unix.

New in version 3.2.

os.putenv(key,value)

Set the environment variable namedkey to the stringvalue. Suchchanges to the environment affect subprocesses started withos.system(),popen() orfork() andexecv().

Availability: most flavors of Unix, Windows.

Note

On some platforms, including FreeBSD and Mac OS X, settingenviron maycause memory leaks. Refer to the system documentation for putenv.

Whenputenv() is supported, assignments to items inos.environ areautomatically translated into corresponding calls toputenv(); however,calls toputenv() don’t updateos.environ, so it is actuallypreferable to assign to items ofos.environ.

Raises anauditing eventos.putenv with argumentskey,value.

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 togroups.groups must be a sequence, and each element must be an integeridentifying a group. This operation is typically available only to the superuser.

Availability: Unix.

Note

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

os.setpgrp()

Call the system callsetpgrp() orsetpgrp(0,0) depending onwhich version is implemented (if any). See the Unix manual for the semantics.

Availability: Unix.

os.setpgid(pid,pgrp)

Call the system callsetpgid() to set the process group id of theprocess with idpid to the process group with idpgrp. See the Unix manualfor the semantics.

Availability: Unix.

os.setpriority(which,who,priority)

Set program scheduling priority. The valuewhich is one ofPRIO_PROCESS,PRIO_PGRP, orPRIO_USER, andwhois interpreted relative towhich (a process identifier forPRIO_PROCESS, process group identifier forPRIO_PGRP, and auser ID forPRIO_USER). A zero value forwho 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.

Availability: Unix.

New in version 3.3.

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

os.setresuid(ruid,euid,suid)

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

Availability: Unix.

New in version 3.2.

os.setreuid(ruid,euid)

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

Availability: Unix.

os.getsid(pid)

Call the system callgetsid(). See the Unix manual for the semantics.

Availability: Unix.

os.setsid()

Call the system callsetsid(). 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 incode.On platforms wherestrerror() returnsNULL when given an unknownerror number,ValueError is raised.

os.supports_bytes_environ

True if the native OS type of the environment is bytes (eg.False onWindows).

New in version 3.2.

os.umask(mask)

Set the current numeric umask and return the previous umask.

os.uname()

Returns information identifying the current operating system.The return value is an object with five attributes:

  • sysname - operating system name

  • nodename - name of machine on network (implementation-defined)

  • release - operating system release

  • version - operating system version

  • machine - hardware identifier

For backwards compatibility, this object is also iterable, behavinglike a five-tuple containingsysname,nodename,release,version, andmachinein that order.

Some systems truncatenodename to 8 characters or to theleading component; a better way to get the hostname issocket.gethostname() or evensocket.gethostbyaddr(socket.gethostname()).

Availability: recent flavors of Unix.

Changed in version 3.3:Return type changed from a tuple to a tuple-like objectwith named attributes.

os.unsetenv(key)

Unset (delete) the environment variable namedkey. Such changes to theenvironment affect subprocesses started withos.system(),popen() orfork() andexecv().

Whenunsetenv() is supported, deletion of items inos.environ isautomatically translated into a corresponding call tounsetenv(); however,calls tounsetenv() don’t updateos.environ, so it is actuallypreferable to delete items ofos.environ.

Raises anauditing eventos.unsetenv with argumentkey.

Availability: most flavors of Unix.

File Object Creation

These functions create newfile objects. (See alsoopen() for opening file descriptors.)

os.fdopen(fd,*args,**kwargs)

Return an open file object connected to the file descriptorfd. This is analias of theopen() built-in function and accepts the same arguments.The only difference is that the first argument offdopen() must alwaysbe an integer.

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 openedby the current process. For example, standard input is usually file descriptor0, standard output is 1, and standard error is 2. Further files opened by aprocess 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 referencedby file descriptors.

Thefileno() method can be used to obtain the file descriptorassociated with afile object when required. Note that using the filedescriptor directly will bypass the file object methods, ignoring aspects suchas internal buffering of data.

os.close(fd)

Close file descriptorfd.

Note

This function is intended for low-level I/O and must be applied to a filedescriptor as returned byos.open() orpipe(). To close a “fileobject” returned by the built-in functionopen() or bypopen() orfdopen(), use itsclose() method.

os.closerange(fd_low,fd_high)

Close all file descriptors fromfd_low (inclusive) tofd_high (exclusive),ignoring errors. Equivalent to (but much faster than):

forfdinrange(fd_low,fd_high):try:os.close(fd)exceptOSError:pass
os.copy_file_range(src,dst,count,offset_src=None,offset_dst=None)

Copycount bytes from file descriptorsrc, starting from offsetoffset_src, to file descriptordst, starting from offsetoffset_dst.Ifoffset_src is None, thensrc is read from the current position;respectively foroffset_dst. The files pointed bysrc anddstmust reside in the same filesystem, otherwise anOSError israised witherrno set toerrno.EXDEV.

This copy is done without the additional cost of transferring datafrom the kernel to user space and then back into the kernel. Additionally,some filesystems could implement extra optimizations. The copy is done as ifboth files are opened as binary.

The return value is the amount of bytes copied. This could be less than theamount requested.

Availability: Linux kernel >= 4.5 or glibc >= 2.27.

New in version 3.8.

os.device_encoding(fd)

Return a string describing the encoding of the device associated withfdif it is connected to a terminal; else returnNone.

os.dup(fd)

Return a duplicate of file descriptorfd. The new file descriptor isnon-inheritable.

On Windows, when duplicating a standard stream (0: stdin, 1: stdout,2: stderr), the new file descriptor isinheritable.

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

os.dup2(fd,fd2,inheritable=True)

Duplicate file descriptorfd tofd2, closing the latter first ifnecessary. Returnfd2. The new file descriptor isinheritable by default or non-inheritable ifinheritableisFalse.

Changed in version 3.4:Add the optionalinheritable parameter.

Changed in version 3.7:Returnfd2 on success. Previously,None was always returned.

os.fchmod(fd,mode)

Change the mode of the file given byfd to the numericmode. See thedocs forchmod() for possible values ofmode. As of Python 3.3, thisis equivalent toos.chmod(fd,mode).

Raises anauditing eventos.chmod with argumentspath,mode,dir_fd.

Availability: Unix.

os.fchown(fd,uid,gid)

Change the owner and group id of the file given byfd to the numericuidandgid. To leave one of the ids unchanged, set it to -1. Seechown(). As of Python 3.3, this is equivalent toos.chown(fd,uid,gid).

Raises anauditing eventos.chown with argumentspath,uid,gid,dir_fd.

Availability: Unix.

os.fdatasync(fd)

Force write of file with filedescriptorfd to disk. Does not force update ofmetadata.

Availability: Unix.

Note

This function is not available on MacOS.

os.fpathconf(fd,name)

Return system configuration information relevant to an open file.namespecifies the configuration value to retrieve; it may be a string which is thename of a defined system value; these names are specified in a number ofstandards (POSIX.1, Unix 95, Unix 98, and others). Some platforms defineadditional names as well. The names known to the host operating system aregiven in thepathconf_names dictionary. For configuration variables notincluded in that mapping, passing an integer forname is also accepted.

Ifname is a string and is not known,ValueError is raised. If aspecific value forname is not supported by the host system, even if it isincluded inpathconf_names, anOSError is raised witherrno.EINVAL for the error number.

As of Python 3.3, this is equivalent toos.pathconf(fd,name).

Availability: Unix.

os.fstat(fd)

Get the status of the file descriptorfd. Return astat_resultobject.

As of Python 3.3, this is equivalent toos.stat(fd).

See also

Thestat() function.

os.fstatvfs(fd)

Return information about the filesystem containing the file associated withfile descriptorfd, likestatvfs(). As of Python 3.3, this isequivalent toos.statvfs(fd).

Availability: Unix.

os.fsync(fd)

Force write of file with filedescriptorfd to disk. On Unix, this calls thenativefsync() function; on Windows, the MS_commit() function.

If you’re starting with a buffered Pythonfile objectf, first dof.flush(), and then doos.fsync(f.fileno()), to ensure that all internalbuffers associated withf are written to disk.

Availability: Unix, Windows.

os.ftruncate(fd,length)

Truncate the file corresponding to file descriptorfd, so that it is atmostlength bytes in size. As of Python 3.3, this is equivalent toos.truncate(fd,length).

Raises anauditing eventos.truncate with argumentsfd,length.

Availability: Unix, Windows.

Changed in version 3.5:Added support for Windows

os.get_blocking(fd)

Get the blocking mode of the file descriptor:False if theO_NONBLOCK flag is set,True if the flag is cleared.

See alsoset_blocking() andsocket.socket.setblocking().

Availability: Unix.

New in version 3.5.

os.isatty(fd)

ReturnTrue if the file descriptorfd is open and connected to atty(-like) device, elseFalse.

os.lockf(fd,cmd,len)

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 ofF_LOCK,F_TLOCK,F_ULOCK orF_TEST.len specifies the section of the file to lock.

Raises anauditing eventos.lockf with argumentsfd,cmd,len.

Availability: Unix.

New in version 3.3.

os.F_LOCK
os.F_TLOCK
os.F_ULOCK
os.F_TEST

Flags that specify what actionlockf() will take.

Availability: Unix.

New in version 3.3.

os.lseek(fd,pos,how)

Set the current position of file descriptorfd to positionpos, modifiedbyhow:SEEK_SET or0 to set the position relative to thebeginning of the file;SEEK_CUR or1 to set it relative to thecurrent position;SEEK_END or2 to set it relative to the end ofthe file. Return the new cursor position in bytes, starting from the beginning.

os.SEEK_SET
os.SEEK_CUR
os.SEEK_END

Parameters to thelseek() function. Their values are 0, 1, and 2,respectively.

New in version 3.3:Some operating systems could support additional values, likeos.SEEK_HOLE oros.SEEK_DATA.

os.open(path,flags,mode=0o777,*,dir_fd=None)

Open the filepath and set various flags according toflags and possiblyits mode according tomode. When computingmode, the current umask valueis first masked out. Return the file descriptor for the newly opened file.The new file descriptor isnon-inheritable.

For a description of the flag and mode values, see the C run-time documentation;flag constants (likeO_RDONLY andO_WRONLY) are defined intheos module. In particular, on Windows addingO_BINARY is needed to open files in binary mode.

This function can supportpaths relative to directory descriptors with thedir_fd parameter.

Raises anauditing eventopen with argumentspath,mode,flags.

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 thebuilt-in functionopen(), which returns afile object withread() andwrite() methods (and many more). Towrap a file descriptor in a file object, usefdopen().

New in version 3.3:Thedir_fd argument.

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

Changed in version 3.6:Accepts apath-like object.

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

os.O_RDONLY
os.O_WRONLY
os.O_RDWR
os.O_APPEND
os.O_CREAT
os.O_EXCL
os.O_TRUNC

The above constants are available on Unix and Windows.

os.O_DSYNC
os.O_RSYNC
os.O_SYNC
os.O_NDELAY
os.O_NONBLOCK
os.O_NOCTTY
os.O_CLOEXEC

The above constants are only available on Unix.

Changed in version 3.3:AddO_CLOEXEC constant.

os.O_BINARY
os.O_NOINHERIT
os.O_SHORT_LIVED
os.O_TEMPORARY
os.O_RANDOM
os.O_SEQUENTIAL
os.O_TEXT

The above constants are only available on Windows.

os.O_ASYNC
os.O_DIRECT
os.O_DIRECTORY
os.O_NOFOLLOW
os.O_NOATIME
os.O_PATH
os.O_TMPFILE
os.O_SHLOCK
os.O_EXLOCK

The above constants are extensions and not present if they are not defined bythe C library.

Changed in version 3.4:AddO_PATH on systems that support it.AddO_TMPFILE, only available on Linux Kernel 3.11 or newer.

os.openpty()

Open a new pseudo-terminal pair. Return a pair of file descriptors(master,slave) for the pty and the tty, respectively. The new filedescriptors arenon-inheritable. For a (slightly) moreportable approach, use thepty module.

Availability: some flavors of Unix.

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

os.pipe()

Create a pipe. Return a pair of file descriptors(r,w) usable forreading and writing, respectively. The new file descriptor isnon-inheritable.

Availability: Unix, Windows.

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

os.pipe2(flags)

Create a pipe withflags 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.

Availability: some flavors of Unix.

New in version 3.3.

os.posix_fallocate(fd,offset,len)

Ensures that enough disk space is allocated for the file specified byfdstarting fromoffset and continuing forlen bytes.

Availability: Unix.

New in version 3.3.

os.posix_fadvise(fd,offset,len,advice)

Announces an intention to access data in a specific pattern thus allowingthe kernel to make optimizations.The advice applies to the region of the file specified byfd starting atoffset and continuing forlen bytes.advice is one ofPOSIX_FADV_NORMAL,POSIX_FADV_SEQUENTIAL,POSIX_FADV_RANDOM,POSIX_FADV_NOREUSE,POSIX_FADV_WILLNEED orPOSIX_FADV_DONTNEED.

Availability: Unix.

New in version 3.3.

os.POSIX_FADV_NORMAL
os.POSIX_FADV_SEQUENTIAL
os.POSIX_FADV_RANDOM
os.POSIX_FADV_NOREUSE
os.POSIX_FADV_WILLNEED
os.POSIX_FADV_DONTNEED

Flags that can be used inadvice inposix_fadvise() that specifythe access pattern that is likely to be used.

Availability: Unix.

New in version 3.3.

os.pread(fd,n,offset)

Read at mostn bytes from file descriptorfd at a position ofoffset,leaving the file offset unchanged.

Return a bytestring containing the bytes read. If the end of the filereferred to byfd has been reached, an empty bytes object is returned.

Availability: Unix.

New in version 3.3.

os.preadv(fd,buffers,offset,flags=0)

Read from a file descriptorfd at a position ofoffset into mutablebytes-like objectsbuffers, leaving the fileoffset unchanged. Transfer data into each buffer until it is full and thenmove on to the next buffer in the sequence to hold the rest of the data.

The flags argument contains a bitwise OR of zero or more of the followingflags:

Return the total number of bytes actually read which can be less than thetotal capacity of all the objects.

The operating system may set a limit (sysconf() value'SC_IOV_MAX') on the number of buffers that can be used.

Combine the functionality ofos.readv() andos.pread().

Availability: Linux 2.6.30 and newer, FreeBSD 6.0 and newer,OpenBSD 2.7 and newer. Using flags requires Linux 4.6 or newer.

New in version 3.7.

os.RWF_NOWAIT

Do not wait for data which is not immediately available. If this flag isspecified, the system call will return instantly if it would have to readdata from the backing storage or wait for a lock.

If some data was successfully read, it will return the number of bytes read.If no bytes were read, it will return-1 and set errno toerrno.EAGAIN.

Availability: Linux 4.14 and newer.

New in version 3.7.

os.RWF_HIPRI

High priority read/write. Allows block-based filesystems to use pollingof the device, which provides lower latency, but may use additionalresources.

Currently, on Linux, this feature is usable only on a file descriptor openedusing theO_DIRECT flag.

Availability: Linux 4.6 and newer.

New in version 3.7.

os.pwrite(fd,str,offset)

Write the bytestring instr to file descriptorfd at position ofoffset, leaving the file offset unchanged.

Return the number of bytes actually written.

Availability: Unix.

New in version 3.3.

os.pwritev(fd,buffers,offset,flags=0)

Write thebuffers contents to file descriptorfd at a offsetoffset,leaving the file offset unchanged.buffers must be a sequence ofbytes-like objects. Buffers are processed inarray order. Entire contents of the first buffer is written beforeproceeding to the second, and so on.

The flags argument contains a bitwise OR of zero or more of the followingflags:

Return the total number of bytes actually written.

The operating system may set a limit (sysconf() value'SC_IOV_MAX') on the number of buffers that can be used.

Combine the functionality ofos.writev() andos.pwrite().

Availability: Linux 2.6.30 and newer, FreeBSD 6.0 and newer,OpenBSD 2.7 and newer. Using flags requires Linux 4.7 or newer.

New in version 3.7.

os.RWF_DSYNC

Provide a per-write equivalent of theO_DSYNCopen(2) flag. Thisflag effect applies only to the data range written by the system call.

Availability: Linux 4.7 and newer.

New in version 3.7.

os.RWF_SYNC

Provide a per-write equivalent of theO_SYNCopen(2) flag. Thisflag effect applies only to the data range written by the system call.

Availability: Linux 4.7 and newer.

New in version 3.7.

os.read(fd,n)

Read at mostn bytes from file descriptorfd.

Return a bytestring containing the bytes read. If the end of the filereferred to byfd 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 filedescriptor as returned byos.open() orpipe(). To read a“file object” returned by the built-in functionopen() or bypopen() orfdopen(), orsys.stdin, use itsread() orreadline() methods.

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

os.sendfile(out,in,offset,count)
os.sendfile(out,in,offset,count,[headers,][trailers,]flags=0)

Copycount bytes from file descriptorin to file descriptoroutstarting atoffset.Return the number of bytes sent. When EOF is reached return 0.

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

On Linux, ifoffset is given asNone, the bytes are read from thecurrent position ofin and the position ofin is updated.

The second case may be used on Mac OS X and FreeBSD whereheaders andtrailers are arbitrary sequences of buffers that are written before andafter the data fromin is written. It returns the same as the first case.

On Mac OS X and FreeBSD, a value of 0 forcount specifies to send untilthe end ofin is reached.

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

Cross-platform applications should not useheaders,trailers andflagsarguments.

Availability: Unix.

Note

For a higher-level wrapper ofsendfile(), seesocket.socket.sendfile().

New in version 3.3.

os.set_blocking(fd,blocking)

Set the blocking mode of the specified file descriptor. Set theO_NONBLOCK flag if blocking isFalse, clear the flag otherwise.

See alsoget_blocking() andsocket.socket.setblocking().

Availability: Unix.

New in version 3.5.

os.SF_NODISKIO
os.SF_MNOWAIT
os.SF_SYNC

Parameters to thesendfile() function, if the implementation supportsthem.

Availability: Unix.

New in version 3.3.

os.readv(fd,buffers)

Read from a file descriptorfd into a number of mutablebytes-likeobjectsbuffers. Transfer data into each buffer untilit is full and then move on to the next buffer in the sequence to hold therest of the data.

Return the total number of bytes actually read which can be less than thetotal capacity of all the objects.

The operating system may set a limit (sysconf() value'SC_IOV_MAX') on the number of buffers that can be used.

Availability: Unix.

New in version 3.3.

os.tcgetpgrp(fd)

Return the process group associated with the terminal given byfd (an openfile descriptor as returned byos.open()).

Availability: Unix.

os.tcsetpgrp(fd,pg)

Set the process group associated with the terminal given byfd (an open filedescriptor as returned byos.open()) topg.

Availability: Unix.

os.ttyname(fd)

Return a string which specifies the terminal device associated withfile descriptorfd. Iffd is not associated with a terminal device, anexception is raised.

Availability: Unix.

os.write(fd,str)

Write the bytestring instr to file descriptorfd.

Return the number of bytes actually written.

Note

This function is intended for low-level I/O and must be applied to a filedescriptor as returned byos.open() orpipe(). To write a “fileobject” returned by the built-in functionopen() or bypopen() orfdopen(), orsys.stdout orsys.stderr, use itswrite() method.

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

os.writev(fd,buffers)

Write the contents ofbuffers to file descriptorfd.buffers must bea sequence ofbytes-like objects. Buffers areprocessed in array order. Entire contents of the first buffer is writtenbefore proceeding to the second, and so on.

Returns the total number of bytes actually written.

The operating system may set a limit (sysconf() value'SC_IOV_MAX') on the number of buffers that can be used.

Availability: Unix.

New in version 3.3.

Querying the size of a terminal

New in version 3.3.

os.get_terminal_size(fd=STDOUT_FILENO)

Return the size of the terminal window as(columns,lines),tuple of typeterminal_size.

The optional argumentfd (defaultSTDOUT_FILENO, or standardoutput) specifies which file descriptor should be queried.

If the file descriptor is not connected to a terminal, anOSErroris raised.

shutil.get_terminal_size() is the high-level function whichshould normally be used,os.get_terminal_size is the low-levelimplementation.

Availability: Unix, Windows.

classos.terminal_size

A subclass of tuple, holding(columns,lines) of the terminal window size.

columns

Width of the terminal window in characters.

lines

Height of the terminal window in characters.

Inheritance of File Descriptors

New in version 3.4.

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

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

On Windows, non-inheritable handles and file descriptors are closed in childprocesses, except for standard streams (file descriptors 0, 1 and 2: stdin, stdoutand stderr), which are always inherited. Usingspawn* functions,all inheritable handles and all inheritable file descriptors are inherited.Using thesubprocess module, all file descriptors except standardstreams are closed, and inheritable handles are only inherited if theclose_fds parameter isFalse.

os.get_inheritable(fd)

Get the “inheritable” flag of the specified file descriptor (a boolean).

os.set_inheritable(fd,inheritable)

Set the “inheritable” flag of the specified file descriptor.

os.get_handle_inheritable(handle)

Get the “inheritable” flag of the specified handle (a boolean).

Availability: Windows.

os.set_handle_inheritable(handle,inheritable)

Set the “inheritable” flag of the specified handle.

Availability: Windows.

Files and Directories

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

  • specifying a file descriptor:Normally thepath argument provided to functions in theos modulemust be a string specifying a file path. However, some functions nowalternatively accept an open file descriptor for theirpath argument.The function will then operate on the file referred to by the descriptor.(For POSIX systems, Python will call the variant of the function prefixedwithf (e.g. callfchdir instead ofchdir).)

    You can check whether or notpath can be specified as a file descriptorfor a particular function on your platform usingos.supports_fd.If this functionality is unavailable, using it will raise aNotImplementedError.

    If the function also supportsdir_fd orfollow_symlinks arguments, it’san error to specify one of those when supplyingpath as a file descriptor.

  • paths relative to directory descriptors: Ifdir_fd is notNone, itshould be a file descriptor referring to a directory, and the path to operateon should be relative; path will then be relative to that directory. If thepath is absolute,dir_fd is ignored. (For POSIX systems, Python will callthe variant of the function with anat suffix and possibly prefixed withf (e.g. callfaccessat instead ofaccess).

    You can check whether or notdir_fd is supported for a particular functionon your platform usingos.supports_dir_fd. If it’s unavailable,using it will raise aNotImplementedError.

  • not following symlinks: Iffollow_symlinks isFalse, and the last element of the path to operate on is a symbolic link,the function will operate on the symbolic link itself rather than the filepointed to by the link. (For POSIX systems, Python will call thel...variant of the function.)

    You can check whether or notfollow_symlinks is supported for a particularfunction on your platform usingos.supports_follow_symlinks.If it’s unavailable, using it will raise aNotImplementedError.

os.access(path,mode,*,dir_fd=None,effective_ids=False,follow_symlinks=True)

Use the real uid/gid to test for access topath. Note that most operationswill use the effective uid/gid, therefore this routine can be used in asuid/sgid environment to test if the invoking user has the specified access topath.mode should beF_OK to test the existence ofpath, or itcan be the inclusive OR of one or more ofR_OK,W_OK, andX_OK to test permissions. ReturnTrue if access is allowed,False if not. See the Unix man pageaccess(2) for moreinformation.

This function can support specifyingpaths relative to directorydescriptors andnot following symlinks.

Ifeffective_ids isTrue,access() will perform its accesschecks using the effective uid/gid instead of the real uid/gid.effective_ids may not be supported on your platform; you can check whetheror not it is available usingos.supports_effective_ids. If it isunavailable, using it will raise aNotImplementedError.

Note

Usingaccess() to check if a user is authorized to e.g. open a filebefore actually doing so usingopen() creates a security hole,because the user might exploit the short time interval between checkingand opening the file to manipulate it. It’s preferable to useEAFPtechniques. For example:

ifos.access("myfile",os.R_OK):withopen("myfile")asfp:returnfp.read()return"some default data"

is better written as:

try:fp=open("myfile")exceptPermissionError:return"some default data"else:withfp:returnfp.read()

Note

I/O operations may fail even whenaccess() indicates that they wouldsucceed, particularly for operations on network filesystems which may havepermissions semantics beyond the usual POSIX permission-bit model.

Changed in version 3.3:Added thedir_fd,effective_ids, andfollow_symlinks parameters.

Changed in version 3.6:Accepts apath-like object.

os.F_OK
os.R_OK
os.W_OK
os.X_OK

Values to pass as themode parameter ofaccess() to test theexistence, readability, writability and executability ofpath,respectively.

os.chdir(path)

Change the current working directory topath.

This function can supportspecifying a file descriptor. Thedescriptor must refer to an opened directory, not an open file.

This function can raiseOSError and subclasses such asFileNotFoundError,PermissionError, andNotADirectoryError.

Raises anauditing eventos.chdir with argumentpath.

New in version 3.3:Added support for specifyingpath as a file descriptoron some platforms.

Changed in version 3.6:Accepts apath-like object.

os.chflags(path,flags,*,follow_symlinks=True)

Set the flags ofpath to the numericflags.flags may take a combination(bitwise OR) of the following values (as defined in thestat module):

This function can supportnot following symlinks.

Raises anauditing eventos.chflags with argumentspath,flags.

Availability: Unix.

New in version 3.3:Thefollow_symlinks argument.

Changed in version 3.6:Accepts apath-like object.

os.chmod(path,mode,*,dir_fd=None,follow_symlinks=True)

Change the mode ofpath to the numericmode.mode may take one of thefollowing values (as defined in thestat module) or bitwise ORedcombinations of them:

This function can supportspecifying a file descriptor,paths relative to directory descriptors andnotfollowing symlinks.

Note

Although Windows supportschmod(), you can only set the file’sread-only flag with it (via thestat.S_IWRITE andstat.S_IREADconstants or a corresponding integer value). All other bits are ignored.

Raises anauditing eventos.chmod with argumentspath,mode,dir_fd.

New in version 3.3:Added support for specifyingpath as an open file descriptor,and thedir_fd andfollow_symlinks arguments.

Changed in version 3.6:Accepts apath-like object.

os.chown(path,uid,gid,*,dir_fd=None,follow_symlinks=True)

Change the owner and group id ofpath to the numericuid andgid. Toleave one of the ids unchanged, set it to -1.

This function can supportspecifying a file descriptor,paths relative to directory descriptors andnotfollowing symlinks.

Seeshutil.chown() for a higher-level function that accepts names inaddition to numeric ids.

Raises anauditing eventos.chown with argumentspath,uid,gid,dir_fd.

Availability: Unix.

New in version 3.3:Added support for specifyingpath as an open file descriptor,and thedir_fd andfollow_symlinks arguments.

Changed in version 3.6:Supports apath-like object.

os.chroot(path)

Change the root directory of the current process topath.

Availability: Unix.

Changed in version 3.6:Accepts apath-like object.

os.fchdir(fd)

Change the current working directory to the directory represented by the filedescriptorfd. The descriptor must refer to an opened directory, not anopen file. As of Python 3.3, this is equivalent toos.chdir(fd).

Raises anauditing eventos.chdir with argumentpath.

Availability: Unix.

os.getcwd()

Return a string representing the current working directory.

os.getcwdb()

Return a bytestring representing the current working directory.

Changed in version 3.8:The function now uses the UTF-8 encoding on Windows, rather than the ANSIcode page: seePEP 529 for the rationale. The function is no longerdeprecated on Windows.

os.lchflags(path,flags)

Set the flags ofpath to the numericflags, likechflags(), but donot follow symbolic links. As of Python 3.3, this is equivalent toos.chflags(path,flags,follow_symlinks=False).

Raises anauditing eventos.chflags with argumentspath,flags.

Availability: Unix.

Changed in version 3.6:Accepts apath-like object.

os.lchmod(path,mode)

Change the mode ofpath to the numericmode. If path is a symlink, thisaffects the symlink rather than the target. See the docs forchmod()for possible values ofmode. As of Python 3.3, this is equivalent toos.chmod(path,mode,follow_symlinks=False).

Raises anauditing eventos.chmod with argumentspath,mode,dir_fd.

Availability: Unix.

Changed in version 3.6:Accepts apath-like object.

os.lchown(path,uid,gid)

Change the owner and group id ofpath to the numericuid andgid. Thisfunction will not follow symbolic links. As of Python 3.3, this is equivalenttoos.chown(path,uid,gid,follow_symlinks=False).

Raises anauditing eventos.chown with argumentspath,uid,gid,dir_fd.

Availability: Unix.

Changed in version 3.6:Accepts apath-like object.

os.link(src,dst,*,src_dir_fd=None,dst_dir_fd=None,follow_symlinks=True)

Create a hard link pointing tosrc nameddst.

This function can support specifyingsrc_dir_fd and/ordst_dir_fd tosupplypaths relative to directory descriptors, andnotfollowing symlinks.

Raises anauditing eventos.link with argumentssrc,dst,src_dir_fd,dst_dir_fd.

Availability: Unix, Windows.

Changed in version 3.2:Added Windows support.

New in version 3.3:Added thesrc_dir_fd,dst_dir_fd, andfollow_symlinks arguments.

Changed in version 3.6:Accepts apath-like object forsrc anddst.

os.listdir(path='.')

Return a list containing the names of the entries in the directory given bypath. The list is in arbitrary order, and does not include the specialentries'.' and'..' even if they are present in the directory.If a file is removed from or added to the directory during the call ofthis function, whether a name for that file be included is unspecified.

path may be apath-like object. Ifpath is of typebytes(directly or indirectly through thePathLike interface),the filenames returned will also be of typebytes;in all other circumstances, they will be of typestr.

This function can also supportspecifying a file descriptor; the file descriptor must refer to a directory.

Raises anauditing eventos.listdir with argumentpath.

Note

To encodestr filenames tobytes, usefsencode().

See also

Thescandir() function returns directory entries along withfile attribute information, giving better performance for manycommon use cases.

Changed in version 3.2:Thepath parameter became optional.

New in version 3.3:Added support for specifyingpath as an open file descriptor.

Changed in version 3.6:Accepts apath-like object.

os.lstat(path,*,dir_fd=None)

Perform the equivalent of anlstat() system call on the given path.Similar tostat(), but does not follow symbolic links. Return astat_result object.

On platforms that do not support symbolic links, this is an alias forstat().

As of Python 3.3, this is equivalent toos.stat(path,dir_fd=dir_fd,follow_symlinks=False).

This function can also supportpaths relative to directory descriptors.

See also

Thestat() function.

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

Changed in version 3.3:Added thedir_fd parameter.

Changed in version 3.6:Accepts apath-like object.

Changed in version 3.8:On Windows, now opens reparse points that represent another path(name surrogates), including symbolic links and directory junctions.Other kinds of reparse points are resolved by the operating system asforstat().

os.mkdir(path,mode=0o777,*,dir_fd=None)

Create a directory namedpath with numeric modemode.

If the directory already exists,FileExistsError is raised.

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

On Windows, amode of0o700 is specifically handled to apply accesscontrol to the new directory such that only the current user andadministrators have access. Other values ofmode are ignored.

This function can also supportpaths relative to directory descriptors.

It is also possible to create temporary directories; see thetempfile module’stempfile.mkdtemp() function.

Raises anauditing eventos.mkdir with argumentspath,mode,dir_fd.

New in version 3.3:Thedir_fd argument.

Changed in version 3.6:Accepts apath-like object.

Changed in version 3.8.20:Windows now handles amode of0o700.

os.makedirs(name,mode=0o777,exist_ok=False)

Recursive directory creation function. Likemkdir(), but makes allintermediate-level directories needed to contain the leaf directory.

Themode parameter is passed tomkdir() for creating the leafdirectory; seethe mkdir() description for how itis interpreted. To set the file permission bits of any newly-created parentdirectories you can set the umask before invokingmakedirs(). Thefile permission bits of existing parent directories are not changed.

Ifexist_ok isFalse (the default), anFileExistsError israised if the target directory already exists.

Note

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

This function handles UNC paths correctly.

Raises anauditing eventos.mkdir with argumentspath,mode,dir_fd.

New in version 3.2:Theexist_ok parameter.

Changed in version 3.4.1:Before Python 3.4.1, ifexist_ok wasTrue and the directory existed,makedirs() would still raise an error ifmode did not match themode of the existing directory. Since this behavior was impossible toimplement safely, it was removed in Python 3.4.1. Seebpo-21082.

Changed in version 3.6:Accepts apath-like object.

Changed in version 3.7:Themode argument no longer affects the file permission bits ofnewly-created intermediate-level directories.

os.mkfifo(path,mode=0o666,*,dir_fd=None)

Create a FIFO (a named pipe) namedpath with numeric modemode.The current umask value is first masked out from the mode.

This function can also supportpaths relative to directory descriptors.

FIFOs are pipes that can be accessed like regular files. FIFOs exist until theyare deleted (for example withos.unlink()). Generally, FIFOs are used asrendezvous between “client” and “server” type processes: the server opens theFIFO for reading, and the client opens it for writing. Note thatmkfifo()doesn’t open the FIFO — it just creates the rendezvous point.

Availability: Unix.

New in version 3.3:Thedir_fd argument.

Changed in version 3.6:Accepts apath-like object.

os.mknod(path,mode=0o600,device=0,*,dir_fd=None)

Create a filesystem node (file, device special file or named pipe) namedpath.mode specifies both the permissions to use and the type of nodeto be created, being combined (bitwise OR) with one ofstat.S_IFREG,stat.S_IFCHR,stat.S_IFBLK, andstat.S_IFIFO (those constants areavailable instat). Forstat.S_IFCHR andstat.S_IFBLK,device defines the newly created device special file (probably usingos.makedev()), otherwise it is ignored.

This function can also supportpaths relative to directory descriptors.

Availability: Unix.

New in version 3.3:Thedir_fd argument.

Changed in version 3.6:Accepts apath-like object.

os.major(device)

Extract the device major number from a raw device number (usually thest_dev orst_rdev field fromstat).

os.minor(device)

Extract the device minor number from a raw device number (usually thest_dev orst_rdev field fromstat).

os.makedev(major,minor)

Compose a raw device number from the major and minor device numbers.

os.pathconf(path,name)

Return system configuration information relevant to a named file.namespecifies the configuration value to retrieve; it may be a string which is thename of a defined system value; these names are specified in a number ofstandards (POSIX.1, Unix 95, Unix 98, and others). Some platforms defineadditional names as well. The names known to the host operating system aregiven in thepathconf_names dictionary. For configuration variables notincluded in that mapping, passing an integer forname is also accepted.

Ifname is a string and is not known,ValueError is raised. If aspecific value forname is not supported by the host system, even if it isincluded inpathconf_names, anOSError is raised witherrno.EINVAL for the error number.

This function can supportspecifying a file descriptor.

Availability: Unix.

Changed in version 3.6:Accepts apath-like object.

os.pathconf_names

Dictionary mapping names accepted bypathconf() andfpathconf() tothe integer values defined for those names by the host operating system. Thiscan be used to determine the set of names known to the system.

Availability: Unix.

os.readlink(path,*,dir_fd=None)

Return a string representing the path to which the symbolic link points. Theresult may be either an absolute or relative pathname; if it is relative, itmay be converted to an absolute pathname usingos.path.join(os.path.dirname(path),result).

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

This function can also supportpaths relative to directory descriptors.

When trying to resolve a path that may contain links, userealpath() to properly handle recursion and platformdifferences.

Availability: Unix, Windows.

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

New in version 3.3:Thedir_fd argument.

Changed in version 3.6:Accepts apath-like object on Unix.

Changed in version 3.8:Accepts apath-like object and a bytes object on Windows.

Changed in version 3.8:Added support for directory junctions, and changed to return thesubstitution path (which typically includes\\?\ prefix) ratherthan the optional “print name” field that was previously returned.

os.remove(path,*,dir_fd=None)

Remove (delete) the filepath. Ifpath is a directory, anIsADirectoryError is raised. Usermdir() to remove directories.If the file does not exist, aFileNotFoundError is raised.

This function can supportpaths relative to directory descriptors.

On Windows, attempting to remove a file that is in use causes an exception tobe raised; on Unix, the directory entry is removed but the storage allocatedto the file is not made available until the original file is no longer in use.

This function is semantically identical tounlink().

Raises anauditing eventos.remove with argumentspath,dir_fd.

New in version 3.3:Thedir_fd argument.

Changed in version 3.6:Accepts apath-like object.

os.removedirs(name)

Remove directories recursively. Works likermdir() except that, if theleaf directory is successfully removed,removedirs() tries tosuccessively remove every parent directory mentioned inpath until an erroris raised (which is ignored, because it generally means that a parent directoryis not empty). For example,os.removedirs('foo/bar/baz') will first removethe directory'foo/bar/baz', and then remove'foo/bar' and'foo' ifthey are empty. RaisesOSError if the leaf directory could not besuccessfully removed.

Raises anauditing eventos.remove with argumentspath,dir_fd.

Changed in version 3.6:Accepts apath-like object.

os.rename(src,dst,*,src_dir_fd=None,dst_dir_fd=None)

Rename the file or directorysrc todst. Ifdst exists, the operationwill fail with anOSError subclass in a number of cases:

On Windows, ifdst exists aFileExistsError is always raised.

On Unix, ifsrc is a file anddst is a directory or vice-versa, anIsADirectoryError or aNotADirectoryError will be raisedrespectively. If both are directories anddst is empty,dst will besilently replaced. Ifdst is a non-empty directory, anOSErroris raised. If both are files,dst it will be replaced silently if the userhas permission. The operation may fail on some Unix flavors ifsrc anddst are on different filesystems. If successful, the renaming will be anatomic operation (this is a POSIX requirement).

This function can support specifyingsrc_dir_fd and/ordst_dir_fd tosupplypaths relative to directory descriptors.

If you want cross-platform overwriting of the destination, usereplace().

Raises anauditing eventos.rename with argumentssrc,dst,src_dir_fd,dst_dir_fd.

New in version 3.3:Thesrc_dir_fd anddst_dir_fd arguments.

Changed in version 3.6:Accepts apath-like object forsrc anddst.

os.renames(old,new)

Recursive directory or file renaming function. Works likerename(), exceptcreation of any intermediate directories needed to make the new pathname good isattempted first. After the rename, directories corresponding to rightmost pathsegments of the old name will be pruned away usingremovedirs().

Note

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

Raises anauditing eventos.rename with argumentssrc,dst,src_dir_fd,dst_dir_fd.

Changed in version 3.6:Accepts apath-like object forold andnew.

os.replace(src,dst,*,src_dir_fd=None,dst_dir_fd=None)

Rename the file or directorysrc todst. Ifdst is a directory,OSError will be raised. Ifdst exists and is a file, it willbe replaced silently if the user has permission. The operation may failifsrc anddst are on different filesystems. If successful,the renaming will be an atomic operation (this is a POSIX requirement).

This function can support specifyingsrc_dir_fd and/ordst_dir_fd tosupplypaths relative to directory descriptors.

Raises anauditing eventos.rename with argumentssrc,dst,src_dir_fd,dst_dir_fd.

New in version 3.3.

Changed in version 3.6:Accepts apath-like object forsrc anddst.

os.rmdir(path,*,dir_fd=None)

Remove (delete) the directorypath. If the directory does not exist or isnot empty, anFileNotFoundError or anOSError is raisedrespectively. In order to remove whole directory trees,shutil.rmtree() can be used.

This function can supportpaths relative to directory descriptors.

Raises anauditing eventos.rmdir with argumentspath,dir_fd.

New in version 3.3:Thedir_fd parameter.

Changed in version 3.6:Accepts apath-like object.

os.scandir(path='.')

Return an iterator ofos.DirEntry objects corresponding to theentries in the directory given bypath. The entries are yielded inarbitrary order, and the special entries'.' and'..' are notincluded. If a file is removed from or added to the directory aftercreating the iterator, whether an entry for that file be included isunspecified.

Usingscandir() instead oflistdir() can significantlyincrease the performance of code that also needs file type or fileattribute information, becauseos.DirEntry objects expose thisinformation if the operating system provides it when scanning a directory.Allos.DirEntry methods may perform a system call, butis_dir() andis_file() usually onlyrequire a system call for symbolic links;os.DirEntry.stat()always requires a system call on Unix but only requires one forsymbolic links on Windows.

path may be apath-like object. Ifpath is of typebytes(directly or indirectly through thePathLike interface),the type of thename andpathattributes of eachos.DirEntry will bebytes; in all othercircumstances, they will be of typestr.

This function can also supportspecifying a file descriptor; the file descriptor must refer to a directory.

Raises anauditing eventos.scandir with argumentpath.

Thescandir() iterator supports thecontext manager protocoland has the following method:

scandir.close()

Close the iterator and free acquired resources.

This is called automatically when the iterator is exhausted or garbagecollected, or when an error happens during iterating. However itis advisable to call it explicitly or use thewithstatement.

New in version 3.6.

The following example shows a simple use ofscandir() to display allthe files (excluding directories) in the givenpath that don’t start with'.'. Theentry.is_file() call will generally not make an additionalsystem call:

withos.scandir(path)asit:forentryinit:ifnotentry.name.startswith('.')andentry.is_file():print(entry.name)

Note

On Unix-based systems,scandir() uses the system’sopendir()andreaddir()functions. On Windows, it uses the Win32FindFirstFileWandFindNextFileWfunctions.

New in version 3.5.

New in version 3.6:Added support for thecontext manager protocol and theclose() method. If ascandir() iterator is neitherexhausted nor explicitly closed aResourceWarning will be emittedin its destructor.

The function accepts apath-like object.

Changed in version 3.7:Added support forfile descriptors on Unix.

classos.DirEntry

Object yielded byscandir() to expose the file path and other fileattributes of a directory entry.

scandir() will provide as much of this information as possible withoutmaking additional system calls. When astat() orlstat() system callis made, theos.DirEntry object will cache the result.

os.DirEntry instances are not intended to be stored in long-lived datastructures; if you know the file metadata has changed or if a long time haselapsed since callingscandir(), callos.stat(entry.path) to fetchup-to-date information.

Because theos.DirEntry methods can make operating system calls, they mayalso raiseOSError. If you need very fine-grainedcontrol over errors, you can catchOSError when calling one of theos.DirEntry methods and handle as appropriate.

To be directly usable as apath-like object,os.DirEntryimplements thePathLike interface.

Attributes and methods on aos.DirEntry instance are as follows:

name

The entry’s base filename, relative to thescandir()pathargument.

Thename attribute will bebytes if thescandir()path argument is of typebytes andstr otherwise. Usefsdecode() to decode byte filenames.

path

The entry’s full path name: equivalent toos.path.join(scandir_path,entry.name) wherescandir_path is thescandir()pathargument. The path is only absolute if thescandir()pathargument was absolute. If thescandir()pathargument was afile descriptor, thepathattribute is the same as thename attribute.

Thepath attribute will bebytes if thescandir()path argument is of typebytes andstr otherwise. Usefsdecode() to decode byte filenames.

inode()

Return the inode number of the entry.

The result is cached on theos.DirEntry object. Useos.stat(entry.path,follow_symlinks=False).st_ino to fetch up-to-dateinformation.

On the first, uncached call, a system call is required on Windows butnot on Unix.

is_dir(*,follow_symlinks=True)

ReturnTrue if this entry is a directory or a symbolic link pointingto a directory; returnFalse if the entry is or points to any otherkind of file, or if it doesn’t exist anymore.

Iffollow_symlinks isFalse, returnTrue only if this entryis a directory (without following symlinks); returnFalse if theentry is any other kind of file or if it doesn’t exist anymore.

The result is cached on theos.DirEntry object, with a separate cacheforfollow_symlinksTrue andFalse. Callos.stat() alongwithstat.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 systemcall, except on certain Unix file systems, such as network file systems,that returndirent.d_type==DT_UNKNOWN. If the entry is a symlink,a system call will be required to follow the symlink unlessfollow_symlinks isFalse.

This method can raiseOSError, such asPermissionError,butFileNotFoundError is caught and not raised.

is_file(*,follow_symlinks=True)

ReturnTrue if this entry is a file or a symbolic link pointing to afile; returnFalse if the entry is or points to a directory or othernon-file entry, or if it doesn’t exist anymore.

Iffollow_symlinks isFalse, returnTrue only if this entryis a file (without following symlinks); returnFalse if the entry isa directory or other non-file entry, or if it doesn’t exist anymore.

The result is cached on theos.DirEntry object. Caching, system callsmade, and exceptions raised are as peris_dir().

is_symlink()

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

The result is cached on theos.DirEntry object. Callos.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 oncertain Unix file systems, such as network file systems, that returndirent.d_type==DT_UNKNOWN.

This method can raiseOSError, such asPermissionError,butFileNotFoundError is caught and not raised.

stat(*,follow_symlinks=True)

Return astat_result object for this entry. This methodfollows symbolic links by default; to stat a symbolic link add thefollow_symlinks=False argument.

On Unix, this method always requires a system call. On Windows, itonly requires a system call iffollow_symlinks isTrue and theentry is a reparse point (for example, a symbolic link or directoryjunction).

On Windows, thest_ino,st_dev andst_nlink attributes of thestat_result are always set to zero. Callos.stat() toget these attributes.

The result is cached on theos.DirEntry object, with a separate cacheforfollow_symlinksTrue andFalse. Callos.stat() tofetch up-to-date information.

Note that there is a nice correspondence between several attributesand methods ofos.DirEntry and ofpathlib.Path. Inparticular, thename attribute has the samemeaning, as do theis_dir(),is_file(),is_symlink()andstat() methods.

New in version 3.5.

Changed in version 3.6:Added support for thePathLike interface. Added supportforbytes paths on Windows.

os.stat(path,*,dir_fd=None,follow_symlinks=True)

Get the status of a file or a file descriptor. Perform the equivalent of astat() system call on the given path.path may be specified aseither a string or bytes – directly or indirectly through thePathLikeinterface – or as an open file descriptor. Return astat_resultobject.

This function normally follows symlinks; to stat a symlink add the argumentfollow_symlinks=False, or uselstat().

This function can supportspecifying a file descriptor andnot following symlinks.

On Windows, passingfollow_symlinks=False will disable following allname-surrogate reparse points, which includes symlinks and directoryjunctions. Other types of reparse points that do not resemble links or thatthe operating system is unable to follow will be opened directly. Whenfollowing a chain of multiple links, this may result in the original linkbeing returned instead of the non-link that prevented full traversal. Toobtain stat results for the final path in this case, use theos.path.realpath() function to resolve the path name as far aspossible and calllstat() on the result. This does not apply todangling symlinks or junction points, which will raise the usual exceptions.

Example:

>>>importos>>>statinfo=os.stat('somefile.txt')>>>statinfoos.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,st_mtime=1297230027, st_ctime=1297230027)>>>statinfo.st_size264

See also

fstat() andlstat() functions.

New in version 3.3:Added thedir_fd andfollow_symlinks arguments, specifying a filedescriptor instead of a path.

Changed in version 3.6:Accepts apath-like object.

Changed in version 3.8:On Windows, all reparse points that can be resolved by the operatingsystem are now followed, and passingfollow_symlinks=Falsedisables following all name surrogate reparse points. If the operatingsystem reaches a reparse point that it is not able to follow,stat nowreturns the information for the original path as iffollow_symlinks=False had been specified instead of raising an error.

classos.stat_result

Object whose attributes correspond roughly to the members of thestat structure. It is used for the result ofos.stat(),os.fstat() andos.lstat().

Attributes:

st_mode

File mode: file type and file mode bits (permissions).

st_ino

Platform dependent, but if non-zero, uniquely identifies thefile for a given value ofst_dev. Typically:

st_dev

Identifier of the device on which this file resides.

st_nlink

Number of hard links.

st_uid

User identifier of the file owner.

st_gid

Group identifier of the file owner.

st_size

Size of the file in bytes, if it is a regular file or a symbolic link.The size of a symbolic link is the length of the pathname it contains,without a terminating null byte.

Timestamps:

st_atime

Time of most recent access expressed in seconds.

st_mtime

Time of most recent content modification expressed in seconds.

st_ctime

Platform dependent:

  • the time of most recent metadata change on Unix,

  • the time of creation on Windows, expressed in seconds.

st_atime_ns

Time of most recent access expressed in nanoseconds as an integer.

st_mtime_ns

Time of most recent content modification expressed in nanoseconds as aninteger.

st_ctime_ns

Platform dependent:

  • the time of most recent metadata change on Unix,

  • the time of creation on Windows, expressed in nanoseconds as aninteger.

Note

The exact meaning and resolution of thest_atime,st_mtime, andst_ctime attributes depend on the operatingsystem and the file system. For example, on Windows systems using the FATor FAT32 file systems,st_mtime has 2-second resolution, andst_atime has only 1-day resolution. See your operating systemdocumentation for details.

Similarly, althoughst_atime_ns,st_mtime_ns,andst_ctime_ns are always expressed in nanoseconds, manysystems do not provide nanosecond precision. On systems that doprovide nanosecond precision, the floating-point object used tostorest_atime,st_mtime, andst_ctimecannot preserve all of it, and as such will be slightly inexact.If you need the exact timestamps you should always usest_atime_ns,st_mtime_ns, andst_ctime_ns.

On some Unix systems (such as Linux), the following attributes may also beavailable:

st_blocks

Number of 512-byte blocks allocated for file.This may be smaller thanst_size/512 when the file has holes.

st_blksize

“Preferred” blocksize for efficient file system I/O. Writing to a file insmaller chunks may cause an inefficient read-modify-rewrite.

st_rdev

Type of device if an inode device.

st_flags

User defined flags for file.

On other Unix systems (such as FreeBSD), the following attributes may beavailable (but may be only filled out if root tries to use them):

st_gen

File generation number.

st_birthtime

Time of file creation.

On Solaris and derivatives, the following attributes may also beavailable:

st_fstype

String that uniquely identifies the type of the filesystem thatcontains the file.

On Mac OS systems, the following attributes may also be available:

st_rsize

Real size of the file.

st_creator

Creator of the file.

st_type

File type.

On Windows systems, the following attributes are also available:

st_file_attributes

Windows file attributes:dwFileAttributes member of theBY_HANDLE_FILE_INFORMATION structure returned byGetFileInformationByHandle(). See theFILE_ATTRIBUTE_*constants in thestat module.

st_reparse_tag

Whenst_file_attributes has theFILE_ATTRIBUTE_REPARSE_POINTset, this field contains the tag identifying the type of reparse point.See theIO_REPARSE_TAG_* constants in thestat module.

The standard modulestat defines functions and constants that areuseful for extracting information from astat structure. (OnWindows, some items are filled with dummy values.)

For backward compatibility, astat_result instance is alsoaccessible as a tuple of at least 10 integers giving the most important (andportable) members of thestat structure, in the orderst_mode,st_ino,st_dev,st_nlink,st_uid,st_gid,st_size,st_atime,st_mtime,st_ctime. More items may be added at the end bysome implementations. For compatibility with older Python versions,accessingstat_result as a tuple always returns integers.

New in version 3.3:Added thest_atime_ns,st_mtime_ns, andst_ctime_ns members.

New in version 3.5:Added thest_file_attributes member on Windows.

Changed in version 3.5:Windows now returns the file index asst_ino whenavailable.

New in version 3.7:Added thest_fstype member to Solaris/derivatives.

New in version 3.8:Added thest_reparse_tag member on Windows.

Changed in version 3.8:On Windows, thest_mode member now identifies specialfiles asS_IFCHR,S_IFIFO orS_IFBLKas appropriate.

os.statvfs(path)

Perform astatvfs() system call on the given path. The return value isan object whose attributes describe the filesystem on the given path, andcorrespond to the members of thestatvfs structure, namely:f_bsize,f_frsize,f_blocks,f_bfree,f_bavail,f_files,f_ffree,f_favail,f_flag,f_namemax,f_fsid.

Two module-level constants are defined for thef_flag attribute’sbit-flags: ifST_RDONLY is set, the filesystem is mountedread-only, and ifST_NOSUID is set, the semantics ofsetuid/setgid bits are disabled or not supported.

Additional module-level constants are defined for GNU/glibc based systems.These areST_NODEV (disallow access to device special files),ST_NOEXEC (disallow program execution),ST_SYNCHRONOUS(writes are synced at once),ST_MANDLOCK (allow mandatory locks on an FS),ST_WRITE (write on file/directory/symlink),ST_APPEND(append-only file),ST_IMMUTABLE (immutable file),ST_NOATIME(do not update access times),ST_NODIRATIME (do not update directory accesstimes),ST_RELATIME (update atime relative to mtime/ctime).

This function can supportspecifying a file descriptor.

Availability: Unix.

Changed in version 3.2:TheST_RDONLY andST_NOSUID constants were added.

New in version 3.3:Added support for specifyingpath as an open file descriptor.

Changed in version 3.4:TheST_NODEV,ST_NOEXEC,ST_SYNCHRONOUS,ST_MANDLOCK,ST_WRITE,ST_APPEND,ST_IMMUTABLE,ST_NOATIME,ST_NODIRATIME,andST_RELATIME constants were added.

Changed in version 3.6:Accepts apath-like object.

New in version 3.7:Addedf_fsid.

os.supports_dir_fd

Aset object indicating which functions in theosmodule accept an open file descriptor for theirdir_fd parameter.Different platforms provide different features, and the underlyingfunctionality Python uses to implement thedir_fd parameter is notavailable on all platforms Python supports. For consistency’s sake,functions that may supportdir_fd always allow specifying theparameter, but will throw an exception if the functionality is usedwhen it’s not locally available. (SpecifyingNone fordir_fdis always supported on all platforms.)

To check whether a particular function accepts an open file descriptorfor itsdir_fd parameter, use thein operator onsupports_dir_fd.As an example, this expression evaluates toTrue ifos.stat()accepts open file descriptors fordir_fd on the local platform:

os.statinos.supports_dir_fd

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

New in version 3.3.

os.supports_effective_ids

Aset object indicating whetheros.access() permitsspecifyingTrue for itseffective_ids parameter on the local platform.(SpecifyingFalse foreffective_ids is always supported on allplatforms.) If the local platform supports it, the collection will containos.access(); otherwise it will be empty.

This expression evaluates toTrue ifos.access() supportseffective_ids=True on the local platform:

os.accessinos.supports_effective_ids

Currentlyeffective_ids is only supported on Unix platforms;it does not work on Windows.

New in version 3.3.

os.supports_fd

Aset object indicating which functions in theos module permit specifying theirpath parameter as an open filedescriptor on the local platform. Different platforms provide differentfeatures, and the underlying functionality Python uses to accept open filedescriptors aspath arguments is not available on all platforms Pythonsupports.

To determine whether a particular function permits specifying an open filedescriptor for itspath parameter, use thein operator onsupports_fd. As an example, this expression evaluates toTrue ifos.chdir() accepts open file descriptors forpath on your localplatform:

os.chdirinos.supports_fd

New in version 3.3.

os.supports_follow_symlinks

Aset object indicating which functions in theos moduleacceptFalse for theirfollow_symlinks parameter on the local platform.Different platforms provide different features, and the underlyingfunctionality Python uses to implementfollow_symlinks is not availableon all platforms Python supports. For consistency’s sake, functions thatmay supportfollow_symlinks always allow specifying the parameter, butwill throw an exception if the functionality is used when it’s not locallyavailable. (SpecifyingTrue forfollow_symlinks is always supportedon all platforms.)

To check whether a particular function acceptsFalse for itsfollow_symlinks parameter, use thein operator onsupports_follow_symlinks. As an example, this expression evaluatestoTrue if you may specifyfollow_symlinks=False when callingos.stat() on the local platform:

os.statinos.supports_follow_symlinks

New in version 3.3.

os.symlink(src,dst,target_is_directory=False,*,dir_fd=None)

Create a symbolic link pointing tosrc nameddst.

On Windows, a symlink represents either a file or a directory, and does notmorph to the target dynamically. If the target is present, the type of thesymlink will be created to match. Otherwise, the symlink will be createdas a directory iftarget_is_directory isTrue or a file symlink (thedefault) otherwise. On non-Windows platforms,target_is_directory is ignored.

This function can supportpaths relative to directory descriptors.

Note

On newer versions of Windows 10, unprivileged accounts can create symlinksif Developer Mode is enabled. When Developer Mode is not available/enabled,theSeCreateSymbolicLinkPrivilege privilege is required, or the processmust be run as an administrator.

OSError is raised when the function is called by an unprivilegeduser.

Raises anauditing eventos.symlink with argumentssrc,dst,dir_fd.

Availability: Unix, Windows.

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

New in version 3.3:Added thedir_fd argument, and now allowtarget_is_directoryon non-Windows platforms.

Changed in version 3.6:Accepts apath-like object forsrc anddst.

Changed in version 3.8:Added support for unelevated symlinks on Windows with Developer Mode.

os.sync()

Force write of everything to disk.

Availability: Unix.

New in version 3.3.

os.truncate(path,length)

Truncate the file corresponding topath, so that it is at mostlength bytes in size.

This function can supportspecifying a file descriptor.

Raises anauditing eventos.truncate with argumentspath,length.

Availability: Unix, Windows.

New in version 3.3.

Changed in version 3.5:Added support for Windows

Changed in version 3.6:Accepts apath-like object.

os.unlink(path,*,dir_fd=None)

Remove (delete) the filepath. This function is semanticallyidentical toremove(); theunlink name is itstraditional Unix name. Please see the documentation forremove() for further information.

Raises anauditing eventos.remove with argumentspath,dir_fd.

New in version 3.3:Thedir_fd parameter.

Changed in version 3.6:Accepts apath-like object.

os.utime(path,times=None,*,[ns,]dir_fd=None,follow_symlinks=True)

Set the access and modified times of the file specified bypath.

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

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

  • Iftimes is notNone,it must be a 2-tuple of the form(atime,mtime)where each member is an int or float expressing seconds.

  • Iftimes isNone andns is unspecified,this is equivalent to specifyingns=(atime_ns,mtime_ns)where both times are the current time.

It is an error to specify tuples for bothtimes andns.

Note that the exact times you set here may not be returned by a subsequentstat() call, depending on the resolution with which your operatingsystem records access and modification times; seestat(). The bestway to preserve exact times is to use thest_atime_ns andst_mtime_nsfields from theos.stat() result object with thens parameter toutime.

This function can supportspecifying a file descriptor,paths relative to directory descriptors andnotfollowing symlinks.

Raises anauditing eventos.utime with argumentspath,times,ns,dir_fd.

New in version 3.3:Added support for specifyingpath as an open file descriptor,and thedir_fd,follow_symlinks, andns parameters.

Changed in version 3.6:Accepts apath-like object.

os.walk(top,topdown=True,onerror=None,followlinks=False)

Generate the file names in a directory tree by walking the treeeither top-down or bottom-up. For each directory in the tree rooted at directorytop (includingtop itself), it yields a 3-tuple(dirpath,dirnames,filenames).

dirpath is a string, the path to the directory.dirnames is a list of thenames of the subdirectories indirpath (excluding'.' and'..').filenames is a list of the names of the non-directory files indirpath.Note that the names in the lists contain no path components. To get a full path(which begins withtop) to a file or directory indirpath, doos.path.join(dirpath,name). Whether or not the lists are sorteddepends on the file system. If a file is removed from or added to thedirpath directory during generating the lists, whether a name for thatfile be included is unspecified.

If optional argumenttopdown isTrue or not specified, the triple for adirectory is generated before the triples for any of its subdirectories(directories are generated top-down). Iftopdown isFalse, the triplefor a directory is generated after the triples for all of its subdirectories(directories are generated bottom-up). No matter the value oftopdown, thelist of subdirectories is retrieved before the tuples for the directory andits subdirectories are generated.

Whentopdown isTrue, the caller can modify thedirnames list in-place(perhaps usingdel or slice assignment), andwalk() will onlyrecurse into the subdirectories whose names remain indirnames; this can beused to prune the search, impose a specific order of visiting, or even to informwalk() about directories the caller creates or renames before it resumeswalk() again. Modifyingdirnames whentopdown isFalse hasno effect on the behavior of the walk, because in bottom-up mode the directoriesindirnames are generated beforedirpath itself is generated.

By default, errors from thescandir() call are ignored. If optionalargumentonerror is specified, it should be a function; it will be called withone argument, anOSError instance. It can report the error to continuewith the walk, or raise the exception to abort the walk. Note that the filenameis available as thefilename attribute of the exception object.

By default,walk() will not walk down into symbolic links that resolve todirectories. Setfollowlinks toTrue to visit directories pointed to bysymlinks, on systems that support them.

Note

Be aware that settingfollowlinks toTrue can lead to infiniterecursion 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 directorybetween resumptions ofwalk().walk() never changes the currentdirectory, and assumes that its caller doesn’t either.

This example displays the number of bytes taken by non-directory files in eachdirectory under the starting directory, except that it doesn’t look under anyCVS subdirectory:

importosfromos.pathimportjoin,getsizeforroot,dirs,filesinos.walk('python/Lib/email'):print(root,"consumes",end=" ")print(sum(getsize(join(root,name))fornameinfiles),end=" ")print("bytes in",len(files),"non-directory files")if'CVS'indirs:dirs.remove('CVS')# don't visit CVS directories

In the next example (simple implementation ofshutil.rmtree()),walking the tree bottom-up is essential,rmdir() doesn’t allowdeleting 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))

Changed in version 3.5:This function now callsos.scandir() instead ofos.listdir(),making it faster by reducing the number of calls toos.stat().

Changed in version 3.6:Accepts apath-like object.

os.fwalk(top='.',topdown=True,onerror=None,*,follow_symlinks=False,dir_fd=None)

This behaves exactly likewalk(), except that it yields a 4-tuple(dirpath,dirnames,filenames,dirfd), and it supportsdir_fd.

dirpath,dirnames andfilenames are identical towalk() output,anddirfd is a file descriptor referring to the directorydirpath.

This function always supportspaths relative to directory descriptors andnot following symlinks. Note howeverthat, unlike other functions, thefwalk() default value forfollow_symlinks isFalse.

Note

Sincefwalk() yields file descriptors, those are only valid untilthe next iteration step, so you should duplicate them (e.g. withdup()) if you want to keep them longer.

This example displays the number of bytes taken by non-directory files in eachdirectory under the starting directory, except that it doesn’t look under anyCVS subdirectory:

importosforroot,dirs,files,rootfdinos.fwalk('python/Lib/email'):print(root,"consumes",end="")print(sum([os.stat(name,dir_fd=rootfd).st_sizefornameinfiles]),end="")print("bytes in",len(files),"non-directory files")if'CVS'indirs:dirs.remove('CVS')# don't visit CVS directories

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

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

Availability: Unix.

New in version 3.3.

Changed in version 3.6:Accepts apath-like object.

Changed in version 3.7:Added support forbytes paths.

os.memfd_create(name[,flags=os.MFD_CLOEXEC])

Create an anonymous file and return a file descriptor that refers to it.flags must be one of theos.MFD_* constants available on the system(or a bitwise ORed combination of them). By default, the new filedescriptor isnon-inheritable.

The name supplied inname is used as a filename and will be displayed asthe target of the corresponding symbolic link in the directory/proc/self/fd/. The displayed name is always prefixed withmemfd:and serves only for debugging purposes. Names do not affect the behavior ofthe file descriptor, and as such multiple files can have the same namewithout any side effects.

Availability: Linux 3.17 or newer with glibc 2.27 or newer.

New in version 3.8.

os.MFD_CLOEXEC
os.MFD_ALLOW_SEALING
os.MFD_HUGETLB
os.MFD_HUGE_SHIFT
os.MFD_HUGE_MASK
os.MFD_HUGE_64KB
os.MFD_HUGE_512KB
os.MFD_HUGE_1MB
os.MFD_HUGE_2MB
os.MFD_HUGE_8MB
os.MFD_HUGE_16MB
os.MFD_HUGE_32MB
os.MFD_HUGE_256MB
os.MFD_HUGE_512MB
os.MFD_HUGE_1GB
os.MFD_HUGE_2GB
os.MFD_HUGE_16GB

These flags can be passed tomemfd_create().

Availability: Linux 3.17 or newer with glibc 2.27 or newer. TheMFD_HUGE* flags are only available since Linux 4.14.

New in version 3.8.

Linux extended attributes

New in version 3.3.

These functions are all available on Linux only.

os.getxattr(path,attribute,*,follow_symlinks=True)

Return the value of the extended filesystem attributeattribute forpath.attribute can be bytes or str (directly or indirectly through thePathLike interface). If it is str, it is encoded with the filesystemencoding.

This function can supportspecifying a file descriptor andnot following symlinks.

Raises anauditing eventos.getxattr with argumentspath,attribute.

Changed in version 3.6:Accepts apath-like object forpath andattribute.

os.listxattr(path=None,*,follow_symlinks=True)

Return a list of the extended filesystem attributes onpath. Theattributes in the list are represented as strings decoded with the filesystemencoding. Ifpath isNone,listxattr() will examine the currentdirectory.

This function can supportspecifying a file descriptor andnot following symlinks.

Raises anauditing eventos.listxattr with argumentpath.

Changed in version 3.6:Accepts apath-like object.

os.removexattr(path,attribute,*,follow_symlinks=True)

Removes the extended filesystem attributeattribute frompath.attribute should be bytes or str (directly or indirectly through thePathLike interface). If it is a string, it is encodedwith the filesystem encoding.

This function can supportspecifying a file descriptor andnot following symlinks.

Raises anauditing eventos.removexattr with argumentspath,attribute.

Changed in version 3.6:Accepts apath-like object forpath andattribute.

os.setxattr(path,attribute,value,flags=0,*,follow_symlinks=True)

Set the extended filesystem attributeattribute onpath tovalue.attribute must be a bytes or str with no embedded NULs (directly orindirectly through thePathLike interface). If it is a str,it is encoded with the filesystem encoding.flags may beXATTR_REPLACE orXATTR_CREATE. IfXATTR_REPLACE isgiven and the attribute does not exist,ENODATA will be raised.IfXATTR_CREATE is given and the attribute already exists, theattribute will not be created andEEXISTS will be raised.

This function can supportspecifying a file descriptor andnot following symlinks.

Note

A bug in Linux kernel versions less than 2.6.39 caused the flags argumentto be ignored on some filesystems.

Raises anauditing eventos.setxattr with argumentspath,attribute,value,flags.

Changed in version 3.6:Accepts apath-like object forpath andattribute.

os.XATTR_SIZE_MAX

The maximum size the value of an extended attribute can be. Currently, thisis 64 KiB on Linux.

os.XATTR_CREATE

This is a possible value for the flags argument insetxattr(). Itindicates the operation must create an attribute.

os.XATTR_REPLACE

This is a possible value for the flags argument insetxattr(). Itindicates the operation must replace an existing attribute.

Process Management

These functions may be used to create and manage processes.

The variousexec* functions take a list of arguments for the newprogram loaded into the process. In each case, the first of these arguments ispassed to the new program as its own name rather than as an argument a user mayhave typed on a command line. For the C programmer, this is theargv[0]passed to a program’smain(). For example,os.execv('/bin/echo',['foo','bar']) will only printbar on standard output;foo will seemto be ignored.

os.abort()

Generate aSIGABRT signal to the current process. On Unix, the defaultbehavior is to produce a core dump; on Windows, the process immediately returnsan exit code of3. Be aware that calling this function will not call thePython signal handler registered forSIGABRT withsignal.signal().

os.add_dll_directory(path)

Add a path to the DLL search path.

This search path is used when resolving dependencies for importedextension modules (the module itself is resolved through sys.path),and also byctypes.

Remove the directory by callingclose() on the returned objector using it in awith statement.

See theMicrosoft documentationfor more information about how DLLs are loaded.

Raises anauditing eventos.add_dll_directory with argumentpath.

Availability: Windows.

New in version 3.8:Previous versions of CPython would resolve DLLs using the defaultbehavior for the current process. This led to inconsistencies,such as only sometimes searchingPATH or the currentworking directory, and OS functions such asAddDllDirectoryhaving no effect.

In 3.8, the two primary ways DLLs are loaded now explicitlyoverride the process-wide behavior to ensure consistency. See theporting notes for information onupdating libraries.

os.execl(path,arg0,arg1,...)
os.execle(path,arg0,arg1,...,env)
os.execlp(file,arg0,arg1,...)
os.execlpe(file,arg0,arg1,...,env)
os.execv(path,args)
os.execve(path,args,env)
os.execvp(file,args)
os.execvpe(file,args,env)

These functions all execute a new program, replacing the current process; theydo 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 asOSError exceptions.

The current process is replaced immediately. Open file objects anddescriptors are not flushed, so if there may be data bufferedon these open files, you should flush them usingsys.stdout.flush() oros.fsync() before calling anexec* function.

The “l” and “v” variants of theexec* functions differ in howcommand-line arguments are passed. The “l” variants are perhaps the easiestto work with if the number of parameters is fixed when the code is written; theindividual parameters simply become additional parameters to theexecl*()functions. The “v” variants are good when the number of parameters isvariable, with the arguments being passed in a list or tuple as theargsparameter. In either case, the arguments to the child process should start withthe name of the command being run, but this is not enforced.

The variants which include a “p” near the end (execlp(),execlpe(),execvp(), andexecvpe()) will use thePATH environment variable to locate the programfile. When theenvironment is being replaced (using one of theexec*e variants,discussed in the next paragraph), the new environment is used as the source ofthePATH variable. The other variants,execl(),execle(),execv(), andexecve(), will not use thePATH variable tolocate the executable;path must contain an appropriate absolute or relativepath.

Forexecle(),execlpe(),execve(), andexecvpe() (notethat these all end in “e”), theenv parameter must be a mapping which isused to define the environment variables for the new process (these are usedinstead of the current process’ environment); the functionsexecl(),execlp(),execv(), andexecvp() all cause the new process toinherit the environment of the current process.

Forexecve() on some platforms,path may also be specified as an openfile descriptor. This functionality may not be supported on your platform;you can check whether or not it is available usingos.supports_fd.If it is unavailable, using it will raise aNotImplementedError.

Raises anauditing eventos.exec with argumentspath,args,env.

Availability: Unix, Windows.

New in version 3.3:Added support for specifyingpath as an open file descriptorforexecve().

Changed in version 3.6:Accepts apath-like object.

os._exit(n)

Exit the process with statusn, without calling cleanup handlers, flushingstdio buffers, etc.

Note

The standard way to exit issys.exit(n)._exit() shouldnormally only be used in the child process after afork().

The following exit codes are defined and can be used with_exit(),although they are not required. These are typically used for system programswritten 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 somevariation. These constants are defined where they are defined by the underlyingplatform.

os.EX_OK

Exit code that means no error occurred.

Availability: Unix.

os.EX_USAGE

Exit code that means the command was used incorrectly, such as when the wrongnumber of arguments are given.

Availability: Unix.

os.EX_DATAERR

Exit code that means the input data was incorrect.

Availability: Unix.

os.EX_NOINPUT

Exit code that means an input file did not exist or was not readable.

Availability: Unix.

os.EX_NOUSER

Exit code that means a specified user did not exist.

Availability: Unix.

os.EX_NOHOST

Exit code that means a specified host did not exist.

Availability: Unix.

os.EX_UNAVAILABLE

Exit code that means that a required service is unavailable.

Availability: Unix.

os.EX_SOFTWARE

Exit code that means an internal software error was detected.

Availability: Unix.

os.EX_OSERR

Exit code that means an operating system error was detected, such as theinability to fork or create a pipe.

Availability: Unix.

os.EX_OSFILE

Exit code that means some system file did not exist, could not be opened, or hadsome other kind of error.

Availability: Unix.

os.EX_CANTCREAT

Exit code that means a user specified output file could not be created.

Availability: Unix.

os.EX_IOERR

Exit code that means that an error occurred while doing I/O on some file.

Availability: Unix.

os.EX_TEMPFAIL

Exit code that means a temporary failure occurred. This indicates somethingthat may not really be an error, such as a network connection that couldn’t bemade during a retryable operation.

Availability: Unix.

os.EX_PROTOCOL

Exit code that means that a protocol exchange was illegal, invalid, or notunderstood.

Availability: Unix.

os.EX_NOPERM

Exit code that means that there were insufficient permissions to perform theoperation (but not intended for file system problems).

Availability: Unix.

os.EX_CONFIG

Exit code that means that some kind of configuration error occurred.

Availability: Unix.

os.EX_NOTFOUND

Exit code that means something like “an entry was not found”.

Availability: Unix.

os.fork()

Fork a child process. Return0 in the child and the child’s process id in theparent. If an error occursOSError is raised.

Note that some platforms including FreeBSD <= 6.3 and Cygwin haveknown issues when usingfork() from a thread.

Raises anauditing eventos.fork with no arguments.

Changed in version 3.8:Callingfork() in a subinterpreter is no longer supported(RuntimeError is raised).

Warning

Seessl for applications that use the SSL module with fork().

Availability: Unix.

os.forkpty()

Fork a child process, using a new pseudo-terminal as the child’s controllingterminal. Return a pair of(pid,fd), wherepid is0 in the child, thenew child’s process id in the parent, andfd is the file descriptor of themaster end of the pseudo-terminal. For a more portable approach, use thepty module. If an error occursOSError is raised.

Raises anauditing eventos.forkpty with no arguments.

Changed in version 3.8:Callingforkpty() in a subinterpreter is no longer supported(RuntimeError is raised).

Availability: some flavors of Unix.

os.kill(pid,sig)

Send signalsig to the processpid. Constants for the specific signalsavailable on the host platform are defined in thesignal module.

Windows: Thesignal.CTRL_C_EVENT andsignal.CTRL_BREAK_EVENT signals are special signals which canonly be sent to console processes which share a common console window,e.g., some subprocesses. Any other value forsig will cause the processto be unconditionally killed by the TerminateProcess API, and the exit codewill be set tosig. The Windows version ofkill() additionally takesprocess handles to be killed.

See alsosignal.pthread_kill().

Raises anauditing eventos.kill with argumentspid,sig.

New in version 3.2:Windows support.

os.killpg(pgid,sig)

Send the signalsig to the process grouppgid.

Raises anauditing eventos.killpg with argumentspgid,sig.

Availability: Unix.

os.nice(increment)

Addincrement to the process’s “niceness”. Return the new niceness.

Availability: Unix.

os.plock(op)

Lock program segments into memory. The value ofop (defined in<sys/lock.h>) determines which segments are locked.

Availability: Unix.

os.popen(cmd,mode='r',buffering=-1)

Open a pipe to or from commandcmd.The return value is an open file objectconnected to the pipe, which can be read or written depending on whethermodeis'r' (default) or'w'. Thebuffering argument has the same meaning asthe corresponding argument to the built-inopen() function. Thereturned file object reads or writes text strings rather than bytes.

Theclose method returnsNone if the subprocess exitedsuccessfully, or the subprocess’s return code if there was anerror. On POSIX systems, if the return code is positive itrepresents the return value of the process left-shifted by onebyte. If the return code is negative, the process was terminatedby the signal given by the negated value of the return code. (Forexample, the return value might be-signal.SIGKILL if thesubprocess was killed.) On Windows systems, the return valuecontains the signed integer return code from the child process.

This is implemented usingsubprocess.Popen; see that class’sdocumentation for more powerful ways to manage and communicate withsubprocesses.

os.posix_spawn(path,argv,env,*,file_actions=None,setpgroup=None,resetids=False,setsid=False,setsigmask=(),setsigdef=(),scheduler=None)

Wraps theposix_spawn() C library API for use from Python.

Most users should usesubprocess.run() instead ofposix_spawn().

The positional-only argumentspath,args, andenv are similar toexecve().

Thepath parameter is the path to the executable file. Thepath shouldcontain a directory. Useposix_spawnp() to pass an executable filewithout directory.

Thefile_actions argument may be a sequence of tuples describing actionsto take on specific file descriptors in the child process between the Clibrary implementation’sfork() andexec() steps.The first item in each tuple must be one of the three type indicatorlisted below describing the remaining tuple elements:

os.POSIX_SPAWN_OPEN

(os.POSIX_SPAWN_OPEN,fd,path,flags,mode)

Performsos.dup2(os.open(path,flags,mode),fd).

os.POSIX_SPAWN_CLOSE

(os.POSIX_SPAWN_CLOSE,fd)

Performsos.close(fd).

os.POSIX_SPAWN_DUP2

(os.POSIX_SPAWN_DUP2,fd,new_fd)

Performsos.dup2(fd,new_fd).

These tuples correspond to the C libraryposix_spawn_file_actions_addopen(),posix_spawn_file_actions_addclose(), andposix_spawn_file_actions_adddup2() API calls used to preparefor theposix_spawn() call itself.

Thesetpgroup argument will set the process group of the child to the valuespecified. If the value specified is 0, the child’s process group ID will bemade the same as its process ID. If the value ofsetpgroup is not set, thechild will inherit the parent’s process group ID. This argument correspondsto the C libraryPOSIX_SPAWN_SETPGROUP flag.

If theresetids argument isTrue it will reset the effective UID andGID of the child to the real UID and GID of the parent process. If theargument isFalse, then the child retains the effective UID and GID ofthe parent. In either case, if the set-user-ID and set-group-ID permissionbits are enabled on the executable file, their effect will override thesetting of the effective UID and GID. This argument corresponds to the ClibraryPOSIX_SPAWN_RESETIDS flag.

If thesetsid argument isTrue, it will create a new session IDforposix_spawn.setsid requiresPOSIX_SPAWN_SETSIDorPOSIX_SPAWN_SETSID_NP flag. Otherwise,NotImplementedErroris raised.

Thesetsigmask argument will set the signal mask to the signal setspecified. If the parameter is not used, then the child inherits theparent’s signal mask. This argument corresponds to the C libraryPOSIX_SPAWN_SETSIGMASK flag.

Thesigdef argument will reset the disposition of all signals in the setspecified. This argument corresponds to the C libraryPOSIX_SPAWN_SETSIGDEF flag.

Thescheduler argument must be a tuple containing the (optional) schedulerpolicy and an instance ofsched_param with the scheduler parameters.A value ofNone in the place of the scheduler policy indicates that isnot being provided. This argument is a combination of the C libraryPOSIX_SPAWN_SETSCHEDPARAM andPOSIX_SPAWN_SETSCHEDULERflags.

Raises anauditing eventos.posix_spawn with argumentspath,argv,env.

New in version 3.8.

Availability: Unix.

os.posix_spawnp(path,argv,env,*,file_actions=None,setpgroup=None,resetids=False,setsid=False,setsigmask=(),setsigdef=(),scheduler=None)

Wraps theposix_spawnp() C library API for use from Python.

Similar toposix_spawn() except that the system searchesfor theexecutable file in the list of directories specified by thePATH environment variable (in the same way as forexecvp(3)).

Raises anauditing eventos.posix_spawn with argumentspath,argv,env.

New in version 3.8.

Availability: Seeposix_spawn() documentation.

os.register_at_fork(*,before=None,after_in_parent=None,after_in_child=None)

Register callables to be executed when a new child process is forkedusingos.fork() or similar process cloning APIs.The parameters are optional and keyword-only.Each specifies a different call point.

  • before is a function called before forking a child process.

  • after_in_parent is a function called from the parent processafter forking a child process.

  • after_in_child is a function called from the child process.

These calls are only made if control is expected to return to thePython interpreter. A typicalsubprocess launch will nottrigger them as the child is not going to re-enter the interpreter.

Functions registered for execution before forking are called inreverse registration order. Functions registered for executionafter forking (either in the parent or in the child) are calledin registration order.

Note thatfork() calls made by third-party C code may notcall those functions, unless it explicitly callsPyOS_BeforeFork(),PyOS_AfterFork_Parent() andPyOS_AfterFork_Child().

There is no way to unregister a function.

Availability: Unix.

New in version 3.7.

os.spawnl(mode,path,...)
os.spawnle(mode,path,...,env)
os.spawnlp(mode,file,...)
os.spawnlpe(mode,file,...,env)
os.spawnv(mode,path,args)
os.spawnve(mode,path,args,env)
os.spawnvp(mode,file,args)
os.spawnvpe(mode,file,args,env)

Execute the programpath in a new process.

(Note that thesubprocess module provides more powerful facilities forspawning new processes and retrieving their results; using that module ispreferable to using these functions. Check especially theReplacing Older Functions with the subprocess Module section.)

Ifmode isP_NOWAIT, this function returns the process id of the newprocess; ifmode isP_WAIT, returns the process’s exit code if itexits normally, or-signal, wheresignal is the signal that killed theprocess. On Windows, the process id will actually be the process handle, so canbe used with thewaitpid() function.

Note on VxWorks, this function doesn’t return-signal when the new process iskilled. Instead it raises OSError exception.

The “l” and “v” variants of thespawn* functions differ in howcommand-line arguments are passed. The “l” variants are perhaps the easiestto work with if the number of parameters is fixed when the code is written; theindividual parameters simply become additional parameters to thespawnl*() functions. The “v” variants are good when the number ofparameters is variable, with the arguments being passed in a list or tuple astheargs parameter. In either case, the arguments to the child process muststart with the name of the command being run.

The variants which include a second “p” near the end (spawnlp(),spawnlpe(),spawnvp(), andspawnvpe()) will use thePATH environment variable to locate the programfile. When theenvironment is being replaced (using one of thespawn*e variants,discussed in the next paragraph), the new environment is used as the source ofthePATH variable. The other variants,spawnl(),spawnle(),spawnv(), andspawnve(), will not use thePATH variable to locate the executable;path must contain anappropriate absolute or relative path.

Forspawnle(),spawnlpe(),spawnve(), andspawnvpe()(note that these all end in “e”), theenv parameter must be a mappingwhich is used to define the environment variables for the new process (they areused instead of the current process’ environment); the functionsspawnl(),spawnlp(),spawnv(), andspawnvp() all causethe new process to inherit the environment of the current process. Note thatkeys and values in theenv dictionary must be strings; invalid keys orvalues will cause the function to fail, with a return value of127.

As an example, the following calls tospawnlp() andspawnvpe() areequivalent:

importosos.spawnlp(os.P_WAIT,'cp','cp','index.html','/dev/null')L=['cp','index.html','/dev/null']os.spawnvpe(os.P_WAIT,'cp',L,os.environ)

Raises anauditing eventos.spawn with argumentsmode,path,args,env.

Availability: Unix, Windows.spawnlp(),spawnlpe(),spawnvp()andspawnvpe() are not available on Windows.spawnle() andspawnve() are not thread-safe on Windows; we advise you to use thesubprocess module instead.

Changed in version 3.6:Accepts apath-like object.

os.P_NOWAIT
os.P_NOWAITO

Possible values for themode parameter to thespawn* family offunctions. If either of these values is given, thespawn*() functionswill return as soon as the new process has been created, with the process id asthe return value.

Availability: Unix, Windows.

os.P_WAIT

Possible value for themode parameter to thespawn* family offunctions. If this is given asmode, thespawn*() functions will notreturn until the new process has run to completion and will return the exit codeof the process the run is successful, or-signal if a signal kills theprocess.

Availability: Unix, Windows.

os.P_DETACH
os.P_OVERLAY

Possible values for themode parameter to thespawn* family offunctions. These are less portable than those listed above.P_DETACHis similar toP_NOWAIT, but the new process is detached from theconsole of the calling process. IfP_OVERLAY is used, the currentprocess will be replaced; thespawn* function will not return.

Availability: Windows.

os.startfile(path[,operation])

Start a file with its associated application.

Whenoperation is not specified or'open', this acts like double-clickingthe file in Windows Explorer, or giving the file name as an argument to thestart command from the interactive command shell: the file is openedwith whatever application (if any) its extension is associated.

When anotheroperation is given, it must be a “command verb” that specifieswhat 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 retrievethe application’s exit status. Thepath parameter is relative to the currentdirectory. If you want to use an absolute path, make sure the first characteris not a slash ('/'); the underlying Win32ShellExecute() functiondoesn’t work if it is. Use theos.path.normpath() function to ensure thatthe path is properly encoded for Win32.

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

Raises anauditing eventos.startfile with argumentspath,operation.

Availability: Windows.

os.system(command)

Execute the command (a string) in a subshell. This is implemented by callingthe Standard C functionsystem(), and has the same limitations.Changes tosys.stdin, etc. are not reflected in the environment ofthe executed command. Ifcommand generates any output, it will be sent tothe interpreter standard output stream.

On Unix, the return value is the exit status of the process encoded in theformat specified forwait(). Note that POSIX does not specify themeaning of the return value of the Csystem() function, so the returnvalue of the Python function is system-dependent.

On Windows, the return value is that returned by the system shell afterrunningcommand. The shell is given by the Windows environment variableCOMSPEC: it is usuallycmd.exe, which returns the exitstatus of the command run; on systems using a non-native shell, consult yourshell documentation.

Thesubprocess module provides more powerful facilities for spawningnew processes and retrieving their results; using that module is preferableto using this function. See theReplacing Older Functions with the subprocess Module section inthesubprocess documentation for some helpful recipes.

Raises anauditing eventos.system with argumentcommand.

Availability: Unix, Windows.

os.times()

Returns the current global process times.The return value is an object with five attributes:

  • user - user time

  • system - system time

  • children_user - user time of all child processes

  • children_system - system time of all child processes

  • elapsed - elapsed real time since a fixed point in the past

For backwards compatibility, this object also behaves like a five-tuplecontaininguser,system,children_user,children_system, andelapsed in that order.

See the Unix manual pagetimes(2) andtimes(3) manual page on Unix orthe GetProcessTimes MSDNon Windows. On Windows, onlyuser andsystem are known; the other attributes are zero.

Availability: Unix, Windows.

Changed in version 3.3:Return type changed from a tuple to a tuple-like objectwith named attributes.

os.wait()

Wait for completion of a child process, and return a tuple containing its pidand exit status indication: a 16-bit number, whose low byte is the signal numberthat killed the process, and whose high byte is the exit status (if the signalnumber is zero); the high bit of the low byte is set if a core file wasproduced.

Availability: Unix.

os.waitid(idtype,id,options)

Wait for the completion of one or more child processes.idtype can beP_PID,P_PGID orP_ALL.id specifies the pid to wait on.options is constructed from the ORing of one or more ofWEXITED,WSTOPPED orWCONTINUED and additionally may be ORed withWNOHANG orWNOWAIT. The return value is an objectrepresenting the data contained in thesiginfo_t structure, namely:si_pid,si_uid,si_signo,si_status,si_code orNone ifWNOHANG is specified and there are nochildren in a waitable state.

Availability: Unix.

New in version 3.3.

os.P_PID
os.P_PGID
os.P_ALL

These are the possible values foridtype inwaitid(). They affecthowid is interpreted.

Availability: Unix.

New in version 3.3.

os.WEXITED
os.WSTOPPED
os.WNOWAIT

Flags that can be used inoptions inwaitid() that specify whatchild signal to wait for.

Availability: Unix.

New in version 3.3.

os.CLD_EXITED
os.CLD_DUMPED
os.CLD_TRAPPED
os.CLD_CONTINUED

These are the possible values forsi_code in the result returned bywaitid().

Availability: Unix.

New in version 3.3.

os.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 idpid, andreturn a tuple containing its process id and exit status indication (encoded asforwait()). The semantics of the call are affected by the value of theintegeroptions, which should be0 for normal operation.

Ifpid is greater than0,waitpid() requests status information forthat specific process. Ifpid is0, the request is for the status of anychild in the process group of the current process. Ifpid is-1, therequest pertains to any child of the current process. Ifpid is less than-1, status is requested for any process in the process group-pid (theabsolute value ofpid).

AnOSError is raised with the value of errno when the syscallreturns -1.

On Windows: Wait for completion of a process given by process handlepid, andreturn a tuple containingpid, and its exit status shifted left by 8 bits(shifting makes cross-platform use of the function easier). Apid less than orequal to0 has no special meaning on Windows, and raises an exception. Thevalue of integeroptions has no effect.pid can refer to any process whoseid is known, not necessarily a child process. Thespawn*functions called withP_NOWAIT return suitable process handles.

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

os.wait3(options)

Similar towaitpid(), except no process id argument is given and a3-element tuple containing the child’s process id, exit status indication,and resource usage information is returned. Refer toresource.getrusage() for details on resource usageinformation. The option argument is the same as that provided towaitpid() andwait4().

Availability: Unix.

os.wait4(pid,options)

Similar towaitpid(), except a 3-element tuple, containing the child’sprocess id, exit status indication, and resource usage information is returned.Refer toresource.getrusage() for details onresource usage information. The arguments towait4() are the sameas those provided towaitpid().

Availability: Unix.

os.WNOHANG

The option forwaitpid() to return immediately if no child process statusis available immediately. The function returns(0,0) in this case.

Availability: Unix.

os.WCONTINUED

This option causes child processes to be reported if they have been continuedfrom a job control stop since their status was last reported.

Availability: some Unix systems.

os.WUNTRACED

This option causes child processes to be reported if they have been stopped buttheir current state has not been reported since they were stopped.

Availability: Unix.

The following functions take a process status code as returned bysystem(),wait(), orwaitpid() as a parameter. They may beused to determine the disposition of a process.

os.WCOREDUMP(status)

ReturnTrue if a core dump was generated for the process, otherwisereturnFalse.

This function should be employed only ifWIFSIGNALED() is true.

Availability: Unix.

os.WIFCONTINUED(status)

ReturnTrue if a stopped child has been resumed by delivery ofSIGCONT (if the process has been continued from a jobcontrol stop), otherwise returnFalse.

SeeWCONTINUED option.

Availability: Unix.

os.WIFSTOPPED(status)

ReturnTrue if the process was stopped by delivery of a signal,otherwise returnFalse.

WIFSTOPPED() only returnsTrue if thewaitpid() call wasdone usingWUNTRACED option or when the process is being traced (seeptrace(2)).

Availability: Unix.

os.WIFSIGNALED(status)

ReturnTrue if the process was terminated by a signal, otherwise returnFalse.

Availability: Unix.

os.WIFEXITED(status)

ReturnTrue if the process exited terminated normally, that is,by callingexit() or_exit(), or by returning frommain();otherwise returnFalse.

Availability: Unix.

os.WEXITSTATUS(status)

Return the process exit status.

This function should be employed only ifWIFEXITED() is true.

Availability: Unix.

os.WSTOPSIG(status)

Return the signal which caused the process to stop.

This function should be employed only ifWIFSTOPPED() is true.

Availability: Unix.

os.WTERMSIG(status)

Return the number of the signal that caused the process to terminate.

This function should be employed only ifWIFSIGNALED() is true.

Availability: Unix.

Interface to the scheduler

These functions control how a process is allocated CPU time by the operatingsystem. They are only available on some Unix platforms. For more detailedinformation, consult your Unix manpages.

New in version 3.3.

The following scheduling policies are exposed if they are supported by theoperating system.

os.SCHED_OTHER

The default scheduling policy.

os.SCHED_BATCH

Scheduling policy for CPU-intensive processes that tries to preserveinteractivity on the rest of the computer.

os.SCHED_IDLE

Scheduling policy for extremely low priority background tasks.

os.SCHED_SPORADIC

Scheduling policy for sporadic server programs.

os.SCHED_FIFO

A First In First Out scheduling policy.

os.SCHED_RR

A round-robin scheduling policy.

os.SCHED_RESET_ON_FORK

This flag can be OR’ed with any other scheduling policy. When a process withthis flag set forks, its child’s scheduling policy and priority are reset tothe default.

classos.sched_param(sched_priority)

This class represents tunable scheduling parameters used insched_setparam(),sched_setscheduler(), andsched_getparam(). It is immutable.

At the moment, there is only one possible parameter:

sched_priority

The scheduling priority for a scheduling policy.

os.sched_get_priority_min(policy)

Get the minimum priority value forpolicy.policy is one of thescheduling policy constants above.

os.sched_get_priority_max(policy)

Get the maximum priority value forpolicy.policy is one of thescheduling policy constants above.

os.sched_setscheduler(pid,policy,param)

Set the scheduling policy for the process with PIDpid. Apid of 0 meansthe calling process.policy is one of the scheduling policy constantsabove.param is asched_param instance.

os.sched_getscheduler(pid)

Return the scheduling policy for the process with PIDpid. Apid of 0means the calling process. The result is one of the scheduling policyconstants above.

os.sched_setparam(pid,param)

Set a scheduling parameters for the process with PIDpid. Apid of 0 meansthe calling process.param is asched_param instance.

os.sched_getparam(pid)

Return the scheduling parameters as asched_param instance for theprocess with PIDpid. Apid of 0 means the calling process.

os.sched_rr_get_interval(pid)

Return the round-robin quantum in seconds for the process with PIDpid. Apid of 0 means the calling process.

os.sched_yield()

Voluntarily relinquish the CPU.

os.sched_setaffinity(pid,mask)

Restrict the process with PIDpid (or the current process if zero) to aset of CPUs.mask is an iterable of integers representing the set ofCPUs to which the process should be restricted.

os.sched_getaffinity(pid)

Return the set of CPUs the process with PIDpid (or the current processif zero) is restricted to.

Miscellaneous System Information

os.confstr(name)

Return string-valued system configuration values.name specifies theconfiguration value to retrieve; it may be a string which is the name of adefined 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 theconfstr_names dictionary. For configuration variables not included in thatmapping, passing an integer forname is also accepted.

If the configuration value specified byname isn’t defined,None isreturned.

Ifname is a string and is not known,ValueError is raised. If aspecific value forname is not supported by the host system, even if it isincluded inconfstr_names, anOSError is raised witherrno.EINVAL for the error number.

Availability: Unix.

os.confstr_names

Dictionary mapping names accepted byconfstr() to the integer valuesdefined for those names by the host operating system. This can be used todetermine the set of names known to the system.

Availability: Unix.

os.cpu_count()

Return the number of CPUs in the system. ReturnsNone if undetermined.

This number is not equivalent to the number of CPUs the current process canuse. The number of usable CPUs can be obtained withlen(os.sched_getaffinity(0))

New in version 3.4.

os.getloadavg()

Return the number of processes in the system run queue averaged over the last1, 5, and 15 minutes or raisesOSError if the load average wasunobtainable.

Availability: Unix.

os.sysconf(name)

Return integer-valued system configuration values. If the configuration valuespecified byname isn’t defined,-1 is returned. The comments regardingthename parameter forconfstr() apply here as well; the dictionary thatprovides information on the known names is given bysysconf_names.

Availability: Unix.

os.sysconf_names

Dictionary mapping names accepted bysysconf() to the integer valuesdefined for those names by the host operating system. This can be used todetermine the set of names known to the system.

Availability: Unix.

The following data values are used to support path manipulation operations. Theseare defined for all platforms.

Higher-level operations on pathnames are defined in theos.path module.

os.curdir

The constant string used by the operating system to refer to the currentdirectory. This is'.' for Windows and POSIX. Also available viaos.path.

os.pardir

The constant string used by the operating system to refer to the parentdirectory. This is'..' for Windows and POSIX. Also available viaos.path.

os.sep

The character used by the operating system to separate pathname components.This is'/' for POSIX and'\\' for Windows. Note that knowing thisis not sufficient to be able to parse or concatenate pathnames — useos.path.split() andos.path.join() — but it is occasionallyuseful. Also available viaos.path.

os.altsep

An alternative character used by the operating system to separate pathnamecomponents, orNone if only one separator character exists. This is set to'/' on Windows systems wheresep is a backslash. Also available viaos.path.

os.extsep

The character which separates the base filename from the extension; for example,the'.' inos.py. Also available viaos.path.

os.pathsep

The character conventionally used by the operating system to separate searchpath components (as inPATH), such as':' for POSIX or';' forWindows. Also available viaos.path.

os.defpath

The default search path used byexec*p* andspawn*p* if the environment doesn’t have a'PATH'key. Also available viaos.path.

os.linesep

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

os.devnull

The file path of the null device. For example:'/dev/null' forPOSIX,'nul' for Windows. Also available viaos.path.

os.RTLD_LAZY
os.RTLD_NOW
os.RTLD_GLOBAL
os.RTLD_LOCAL
os.RTLD_NODELETE
os.RTLD_NOLOAD
os.RTLD_DEEPBIND

Flags for use with thesetdlopenflags() andgetdlopenflags() functions. See the Unix manual pagedlopen(3) for what the different flags mean.

New in version 3.3.

Random numbers

os.getrandom(size,flags=0)

Get up tosize random bytes. The function can return less bytes thanrequested.

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

getrandom() relies on entropy gathered from device drivers and othersources of environmental noise. Unnecessarily reading large quantities ofdata 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 thefollowing values ORed together:os.GRND_RANDOM andGRND_NONBLOCK.

See also theLinux getrandom() manual page.

Availability: Linux 3.17 and newer.

New in version 3.6.

os.urandom(size)

Return a string ofsize random bytes suitable for cryptographic use.

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

On Linux, if thegetrandom() syscall is available, it is used inblocking mode: block until the system urandom entropy pool is initialized(128 bits of entropy are collected by the kernel). See thePEP 524 forthe rationale. On Linux, thegetrandom() function can be used to getrandom bytes in non-blocking mode (using theGRND_NONBLOCK flag) orto poll until the system urandom entropy pool is initialized.

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

On Windows, it will useCryptGenRandom().

See also

Thesecrets module provides higher level functions. For aneasy-to-use interface to the random number generator provided by yourplatform, please seerandom.SystemRandom.

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

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

Changed in version 3.5:On Linux 3.17 and newer, thegetrandom() syscall is now usedwhen available. On OpenBSD 5.6 and newer, the Cgetentropy()function is now used. These functions avoid the usage of an internal filedescriptor.

os.GRND_NONBLOCK

By default, when reading from/dev/random,getrandom() blocks ifno random bytes are available, and when reading from/dev/urandom, it blocksif the entropy pool has not yet been initialized.

If theGRND_NONBLOCK flag is set, thengetrandom() does notblock in these cases, but instead immediately raisesBlockingIOError.

New in version 3.6.

os.GRND_RANDOM

If this bit is set, then random bytes are drawn from the/dev/random pool instead of the/dev/urandom pool.

New in version 3.6.