15.1.os — Miscellaneous operating system interfaces

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.

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

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

Note

All functions in this module raiseOSError in the case of invalid orinaccessible file names and paths, or other arguments that have the correcttype, 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','os2','ce','java','riscos'.

See also

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

Theplatform module provides detailed checks for thesystem’s identity.

15.1.1.Process Parameters

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

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.

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.

Changed in version 2.6:Also unset environment variables when callingos.environ.clear()andos.environ.pop().

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

These functions are described inFiles and Directories.

os.ctermid()

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

Availability: Unix.

os.getegid()

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

Availability: Unix.

os.geteuid()

Return the current process’s effective user id.

Availability: Unix.

os.getgid()

Return the real group id of the current process.

Availability: Unix.

os.getgroups()

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

Availability: Unix.

Note

On Mac OS X,getgroups() behavior differs somewhat 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.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 2.7.

os.getlogin()

Return the name of the user logged in on the controlling terminal of theprocess. For most purposes, it is more useful to use the environmentvariableLOGNAME to find out who the user is, orpwd.getpwuid(os.getuid())[0] to get the login name of the process’s realuser id.

Availability: Unix.

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.

New in version 2.3.

os.getpgrp()

Return the id of the current process group.

Availability: Unix.

os.getpid()

Return the current process id.

Availability: Unix, Windows.

os.getppid()

Return the parent’s process id.

Availability: Unix.

os.getresuid()

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

Availability: Unix.

New in version 2.7.

os.getresgid()

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

Availability: Unix.

New in version 2.7.

os.getuid()

Return the current process’s real user id.

Availability: Unix.

os.getenv(varname[,value])

Return the value of the environment variablevarname if it exists, orvalueif it doesn’t.value defaults toNone.

Availability: most flavors of Unix, Windows.

os.putenv(varname,value)

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

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.

New in version 2.2.

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.setregid(rgid,egid)

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

Availability: Unix.

os.setresgid(rgid,egid,sgid)

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

Availability: Unix.

New in version 2.7.

os.setresuid(ruid,euid,suid)

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

Availability: Unix.

New in version 2.7.

os.setreuid(ruid,euid)

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

Availability: Unix.

os.getsid(pid)

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

Availability: Unix.

New in version 2.4.

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.

Availability: Unix, Windows.

os.umask(mask)

Set the current numeric umask and return the previous umask.

Availability: Unix, Windows.

os.uname()

Return a 5-tuple containing information identifying the current operatingsystem. The tuple contains 5 strings:(sysname,nodename,release,version,machine). Some systems truncate the nodename 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.

os.unsetenv(varname)

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

Availability: most flavors of Unix, Windows.

15.1.2.File Object Creation

These functions create new file objects. (See alsoopen().)

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

Return an open file object connected to the file descriptorfd. Themodeandbufsize arguments have the same meaning as the corresponding argumentsto the built-inopen() function. Iffdopen() raises anexception, it leavesfd untouched (unclosed).

Availability: Unix, Windows.

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

Changed in version 2.5:On Unix, when themode argument starts with'a', theO_APPEND flag isset on the file descriptor (which thefdopen() implementation alreadydoes on most platforms).

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

Open a pipe to or fromcommand. The return value is an open file objectconnected to the pipe, which can be read or written depending on whethermodeis'r' (default) or'w'. Thebufsize argument has the same meaning asthe corresponding argument to the built-inopen() function. The exitstatus of the command (encoded in the format specified forwait()) isavailable as the return value of theclose() method of the file object,except that when the exit status is zero (termination without errors),Noneis returned.

Availability: Unix, Windows.

Deprecated since version 2.6:This function is obsolete. Use thesubprocess module. Checkespecially theReplacing Older Functions with the subprocess Module section.

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

os.tmpfile()

Return a new file object opened in update mode (w+b). The file has nodirectory entries associated with it and will be automatically deleted oncethere are no file descriptors for the file.

Availability: Unix, Windows.

There are a number of differentpopen*() functions that provide slightlydifferent ways to create subprocesses.

Deprecated since version 2.6:All of thepopen*() functions are obsolete. Use thesubprocessmodule.

For each of thepopen*() variants, ifbufsize is specified, itspecifies the buffer size for the I/O pipes.mode, if provided, should be thestring'b' or't'; on Windows this is needed to determine whether thefile objects should be opened in binary or text mode. The default value formode is't'.

Also, for each of these variants, on Unix,cmd may be a sequence, in whichcase arguments will be passed directly to the program without shell intervention(as withos.spawnv()). Ifcmd is a string it will be passed to the shell(as withos.system()).

These methods do not make it possible to retrieve the exit status from the childprocesses. The only way to control the input and output streams and alsoretrieve the return codes is to use thesubprocess module; these are onlyavailable on Unix.

For a discussion of possible deadlock conditions related to the use of thesefunctions, seeFlow Control Issues.

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

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

Deprecated since version 2.6:This function is obsolete. Use thesubprocess module. Checkespecially theReplacing Older Functions with the subprocess Module section.

Availability: Unix, Windows.

New in version 2.0.

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

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

Deprecated since version 2.6:This function is obsolete. Use thesubprocess module. Checkespecially theReplacing Older Functions with the subprocess Module section.

Availability: Unix, Windows.

New in version 2.0.

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

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

Deprecated since version 2.6:This function is obsolete. Use thesubprocess module. Checkespecially theReplacing Older Functions with the subprocess Module section.

Availability: Unix, Windows.

New in version 2.0.

(Note thatchild_stdin,child_stdout,andchild_stderr are named from thepoint of view of the child process, sochild_stdin is the child’s standardinput.)

This functionality is also available in thepopen2 module using functionsof the same names, but the return values of those functions have a differentorder.

15.1.3.File Descriptor Operations

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

File descriptors are small integers corresponding to a file that has been 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 a file 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.

Availability: Unix, Windows.

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:

forfdinxrange(fd_low,fd_high):try:os.close(fd)exceptOSError:pass

Availability: Unix, Windows.

New in version 2.6.

os.dup(fd)

Return a duplicate of file descriptorfd.

Availability: Unix, Windows.

os.dup2(fd,fd2)

Duplicate file descriptorfd tofd2, closing the latter first if necessary.

Availability: Unix, Windows.

os.fchmod(fd,mode)

Change the mode of the file given byfd to the numericmode. See the docsforchmod() for possible values ofmode.

Availability: Unix.

New in version 2.6.

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.

Availability: Unix.

New in version 2.6.

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.

Availability: Unix.

os.fstat(fd)

Return status for file descriptorfd, likestat().

Availability: Unix, Windows.

os.fstatvfs(fd)

Return information about the filesystem containing the file associated with filedescriptorfd, likestatvfs().

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 Python file objectf, first dof.flush(), andthen doos.fsync(f.fileno()), to ensure that all internal buffers associatedwithf are written to disk.

Availability: Unix, and Windows starting in 2.2.3.

os.ftruncate(fd,length)

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

Availability: Unix.

os.isatty(fd)

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

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.

Availability: Unix, Windows.

os.SEEK_SET
os.SEEK_CUR
os.SEEK_END

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

Availability: Windows, Unix.

New in version 2.5.

os.open(file,flags[,mode])

Open the filefile and set various flags according toflags and possibly itsmode according tomode. The defaultmode is0777 (octal), and thecurrent umask value is first masked out. Return the file descriptor for thenewly opened file.

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

Availability: Unix, Windows.

Note

This function is intended for low-level I/O. For normal usage, use thebuilt-in functionopen(), which returns a “file object” withread() andwrite() methods (and many more). Towrap a file descriptor in a “file object”, usefdopen().

os.openpty()

Open a new pseudo-terminal pair. Return a pair of file descriptors(master,slave) for the pty and the tty, respectively. For a (slightly) more portableapproach, use thepty module.

Availability: some flavors of Unix.

os.pipe()

Create a pipe. Return a pair of file descriptors(r,w) usable for readingand writing, respectively.

Availability: Unix, Windows.

os.read(fd,n)

Read at mostn bytes from file descriptorfd. Return a string containing thebytes read. If the end of the file referred to byfd has been reached, anempty string is returned.

Availability: Unix, Windows.

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.

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 stringstr to file descriptorfd. Return the number of bytesactually written.

Availability: Unix, Windows.

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.

15.1.3.1.open() flag constants

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

The above constants are only available on Unix.

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_SHLOCK
os.O_EXLOCK

The above constants are extensions and not present if they are notdefined by the C library.

15.1.4.Files and Directories

os.access(path,mode)

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.

Availability: Unix, Windows.

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")exceptIOErrorase:ife.errno==errno.EACCES:return"some default data"# Not a permission error.raiseelse: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.

os.F_OK

Value to pass as themode parameter ofaccess() to test the existence ofpath.

os.R_OK

Value to include in themode parameter ofaccess() to test thereadability ofpath.

os.W_OK

Value to include in themode parameter ofaccess() to test thewritability ofpath.

os.X_OK

Value to include in themode parameter ofaccess() to determine ifpath can be executed.

os.chdir(path)

Change the current working directory topath.

Availability: Unix, Windows.

os.fchdir(fd)

Change the current working directory to the directory represented by the filedescriptorfd. The descriptor must refer to an opened directory, not an openfile.

Availability: Unix.

New in version 2.3.

os.getcwd()

Return a string representing the current working directory.

Availability: Unix, Windows.

os.getcwdu()

Return a Unicode object representing the current working directory.

Availability: Unix, Windows.

New in version 2.3.

os.chflags(path,flags)

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

Availability: Unix.

New in version 2.6.

os.chroot(path)

Change the root directory of the current process topath. Availability:Unix.

New in version 2.2.

os.chmod(path,mode)

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

Availability: Unix, Windows.

Note

Although Windows supportschmod(), you can only set the file’s read-onlyflag with it (via thestat.S_IWRITE andstat.S_IREADconstants or a corresponding integer value). All other bits areignored.

os.chown(path,uid,gid)

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

Availability: Unix.

os.lchflags(path,flags)

Set the flags ofpath to the numericflags, likechflags(), but do notfollow symbolic links.

Availability: Unix.

New in version 2.6.

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.

Availability: Unix.

New in version 2.6.

os.lchown(path,uid,gid)

Change the owner and group id ofpath to the numericuid andgid. Thisfunction will not follow symbolic links.

Availability: Unix.

New in version 2.3.

os.link(source,link_name)

Create a hard link pointing tosource namedlink_name.

Availability: Unix.

os.listdir(path)

Return a list containing the names of the entries in the directory given bypath. The list is in arbitrary order. It does not include the specialentries'.' and'..' even if they are present in thedirectory.

Availability: Unix, Windows.

Changed in version 2.3:On Windows NT/2k/XP and Unix, ifpath is a Unicode object, the result will bea list of Unicode objects. Undecodable filenames will still be returned asstring objects.

os.lstat(path)

Perform the equivalent of anlstat() system call on the given path.Similar tostat(), but does not follow symbolic links. Onplatforms that do not support symbolic links, this is an alias forstat().

os.mkfifo(path[,mode])

Create a FIFO (a named pipe) namedpath with numeric modemode. The defaultmode is0666 (octal). The current umask value is first masked out fromthe mode.

Availability: Unix.

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.

os.mknod(filename[,mode=0600[,device=0]])

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

New in version 2.3.

os.major(device)

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

New in version 2.3.

os.minor(device)

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

New in version 2.3.

os.makedev(major,minor)

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

New in version 2.3.

os.mkdir(path[,mode])

Create a directory namedpath with numeric modemode. The defaultmode is0777 (octal). If the directory already exists,OSError 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.

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

Availability: Unix, Windows.

os.makedirs(path[,mode])

Recursive directory creation function. Likemkdir(), but makes allintermediate-level directories needed to contain the leaf directory. Raises anerror exception if the leaf directory already exists or cannot becreated. The defaultmode is0777 (octal).

Themode parameter is passed tomkdir(); seethe mkdir()description for how it is interpreted.

Note

makedirs() will become confused if the path elements to create includeos.pardir.

New in version 1.5.2.

Changed in version 2.3:This function now handles UNC paths correctly.

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.

Availability: Unix.

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)

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, it maybe converted to an absolute pathname usingos.path.join(os.path.dirname(path),result).

Changed in version 2.6:If thepath is a Unicode object the result will also be a Unicode object.

Availability: Unix.

os.remove(path)

Remove (delete) the filepath. Ifpath is a directory,OSError israised; seermdir() below to remove a directory. This is identical totheunlink() function documented below. On Windows, attempting toremove a file that is in use causes an exception to be raised; on Unix, thedirectory entry is removed but the storage allocated to the file is not madeavailable until the original file is no longer in use.

Availability: Unix, Windows.

os.removedirs(path)

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.

New in version 1.5.2.

os.rename(src,dst)

Rename the file or directorysrc todst. Ifdst is a directory,OSError will be raised. On Unix, ifdst exists and is a file, it willbe replaced silently if the user has permission. The operation may fail on someUnix flavors ifsrc anddst are on different filesystems. If successful,the renaming will be an atomic operation (this is a POSIX requirement). OnWindows, ifdst already exists,OSError will be raised even if it is afile; there may be no way to implement an atomic rename whendst names anexisting file.

Availability: Unix, Windows.

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

New in version 1.5.2.

Note

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

os.rmdir(path)

Remove (delete) the directorypath. Only works when the directory isempty, otherwise,OSError is raised. In order to remove wholedirectory trees,shutil.rmtree() can be used.

Availability: Unix, Windows.

os.stat(path)

Perform the equivalent of astat() system call on the given path.(This function follows symlinks; to stat a symlink uselstat().)

The return value is an object whose attributes correspond to the membersof thestat structure, namely:

  • st_mode - protection bits,

  • st_ino - inode number,

  • st_dev - device,

  • st_nlink - number of hard links,

  • st_uid - user id of owner,

  • st_gid - group id of owner,

  • st_size - size of file, in bytes,

  • st_atime - time of most recent access,

  • st_mtime - time of most recent content modification,

  • st_ctime - platform dependent; time of most recent metadata change onUnix, or the time of creation on Windows)

Changed in version 2.3:Ifstat_float_times() returnsTrue, the time values are floats, measuringseconds. Fractions of a second may be reported if the system supports that.Seestat_float_times() for further discussion.

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

  • st_blocks - number of 512-byte blocks allocated for file

  • st_blksize - filesystem blocksize for efficient file system I/O

  • 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 RISCOS systems, the following attributes are also available:

  • st_ftype (file type)

  • st_attrs (attributes)

  • st_obtype (object type).

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.

For backward compatibility, the return value ofstat() is also accessibleas a tuple of at least 10 integers giving the most important (and portable)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 by some implementations.

The standard modulestat defines functions and constants that are usefulfor extracting information from astat structure. (On Windows, someitems are filled with dummy values.)

Example:

>>>importos>>>statinfo=os.stat('somefile.txt')>>>statinfo(33188, 422511, 769, 1, 1032, 100, 926, 1105022698,1105022732, 1105022732)>>>statinfo.st_size926

Availability: Unix, Windows.

Changed in version 2.2:Added access to values as attributes of the returned object.

Changed in version 2.5:Addedst_gen andst_birthtime.

os.stat_float_times([newvalue])

Determine whetherstat_result represents time stamps as float objects.Ifnewvalue isTrue, future calls tostat() return floats, if it isFalse, future calls return ints. Ifnewvalue is omitted, return thecurrent setting.

For compatibility with older Python versions, accessingstat_result asa tuple always returns integers.

Changed in version 2.5:Python now returns float values by default. Applications which do not workcorrectly with floating point time stamps can use this function to restore theold behaviour.

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

It is recommended that this setting is only changed at program startup time inthe__main__ module; libraries should never change this setting. If anapplication uses a library that works incorrectly if floating point time stampsare processed, this application should turn the feature off until the libraryhas been corrected.

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.

For backward compatibility, the return value is also accessible as a tuple whosevalues correspond to the attributes, in the order given above. The standardmodulestatvfs defines constants that are useful for extractinginformation from astatvfs structure when accessing it as a sequence;this remains useful when writing code that needs to work with versions of Pythonthat don’t support accessing the fields as attributes.

Availability: Unix.

Changed in version 2.2:Added access to values as attributes of the returned object.

os.symlink(source,link_name)

Create a symbolic link pointing tosource namedlink_name.

Availability: Unix.

os.tempnam([dir[,prefix]])

Return a unique path name that is reasonable for creating a temporary file.This will be an absolute path that names a potential directory entry in thedirectorydir or a common location for temporary files ifdir is omitted orNone. If given and notNone,prefix is used to provide a short prefixto the filename. Applications are responsible for properly creating andmanaging files created using paths returned bytempnam(); no automaticcleanup is provided. On Unix, the environment variableTMPDIRoverridesdir, while on WindowsTMP is used. The specificbehavior of this function depends on the C library implementation; some aspectsare underspecified in system documentation.

Warning

Use oftempnam() is vulnerable to symlink attacks; consider usingtmpfile() (sectionFile Object Creation) instead.

Availability: Unix, Windows.

os.tmpnam()

Return a unique path name that is reasonable for creating a temporary file.This will be an absolute path that names a potential directory entry in a commonlocation for temporary files. Applications are responsible for properlycreating and managing files created using paths returned bytmpnam(); noautomatic cleanup is provided.

Warning

Use oftmpnam() is vulnerable to symlink attacks; consider usingtmpfile() (sectionFile Object Creation) instead.

Availability: Unix, Windows. This function probably shouldn’t be used onWindows, though: Microsoft’s implementation oftmpnam() always creates aname in the root directory of the current drive, and that’s generally a poorlocation for a temp file (depending on privileges, you may not even be able toopen a file using this name).

os.TMP_MAX

The maximum number of unique names thattmpnam() will generate beforereusing names.

os.unlink(path)

Remove (delete) the filepath. This is the same function asremove(); theunlink() name is its traditional Unixname.

Availability: Unix, Windows.

os.utime(path,times)

Set the access and modified times of the file specified bypath. IftimesisNone, then the file’s access and modified times are set to the currenttime. (The effect is similar to running the Unix programtouch onthe path.) Otherwise,times must be a 2-tuple of numbers, of the form(atime,mtime) which is used to set the access and modified times,respectively. Whether a directory can be given forpath depends on whetherthe operating system implements directories as files (for example, Windowsdoes not). Note that the exact times you set here may not be returned by asubsequentstat() call, depending on the resolution with which youroperating system records access and modification times; seestat().

Changed in version 2.0:Added support forNone fortimes.

Availability: Unix, Windows.

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

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

New in version 2.6:Thefollowlinks parameter.

Note

Be aware that settingfollowlinks toTrue can lead to infinite recursion if alink points to a parent directory of itself.walk() does not keep track ofthe 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'):printroot,"consumes",printsum(getsize(join(root,name))fornameinfiles),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 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))

New in version 2.3.

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

Availability: Unix, Windows.

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.

Availability: Unix, Windows.

os._exit(n)

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

Availability: Unix, Windows.

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.

New in version 2.3.

os.EX_USAGE

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

Availability: Unix.

New in version 2.3.

os.EX_DATAERR

Exit code that means the input data was incorrect.

Availability: Unix.

New in version 2.3.

os.EX_NOINPUT

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

Availability: Unix.

New in version 2.3.

os.EX_NOUSER

Exit code that means a specified user did not exist.

Availability: Unix.

New in version 2.3.

os.EX_NOHOST

Exit code that means a specified host did not exist.

Availability: Unix.

New in version 2.3.

os.EX_UNAVAILABLE

Exit code that means that a required service is unavailable.

Availability: Unix.

New in version 2.3.

os.EX_SOFTWARE

Exit code that means an internal software error was detected.

Availability: Unix.

New in version 2.3.

os.EX_OSERR

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

Availability: Unix.

New in version 2.3.

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.

New in version 2.3.

os.EX_CANTCREAT

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

Availability: Unix.

New in version 2.3.

os.EX_IOERR

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

Availability: Unix.

New in version 2.3.

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.

New in version 2.3.

os.EX_PROTOCOL

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

Availability: Unix.

New in version 2.3.

os.EX_NOPERM

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

Availability: Unix.

New in version 2.3.

os.EX_CONFIG

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

Availability: Unix.

New in version 2.3.

os.EX_NOTFOUND

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

Availability: Unix.

New in version 2.3.

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, Cygwin and OS/2 EMX haveknown issues when using fork() from a thread.

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.

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.

New in version 2.7:Windows support

os.killpg(pgid,sig)

Send the signalsig to the process grouppgid.

Availability: Unix.

New in version 2.3.

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(...)
os.popen2(...)
os.popen3(...)
os.popen4(...)

Run child processes, returning opened pipes for communications. These functionsare described in sectionFile Object Creation.

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.

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)

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.

New in version 1.6.

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.

New in version 1.6.

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.

New in version 1.6.

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.

New in version 1.6.

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.

Availability: Windows.

New in version 2.0.

New in version 2.5:Theoperation parameter.

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 of theexecuted command.

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

On Windows, the return value is that returned by the system shell after runningcommand, given by the Windows environment variableCOMSPEC: oncommand.com systems (Windows 95, 98 and ME) this is always0; oncmd.exe systems (Windows NT, 2000 and XP) this is the exit status ofthe command run; on systems using a non-native shell, consult your shelldocumentation.

Thesubprocess module provides more powerful facilities for spawning newprocesses and retrieving their results; using that module is preferable to usingthis function. See theReplacing Older Functions with the subprocess Module section in thesubprocess documentationfor some helpful recipes.

Availability: Unix, Windows.

os.times()

Return a 5-tuple of floating point numbers indicating accumulated (processoror other) times, in seconds. The items are: user time, system time,children’s user time, children’s system time, and elapsed real time since afixed point in the past, in that order. See the Unix manual pagetimes(2) or the corresponding Windows Platform API documentation.On Windows, only the first two items are filled, the others are zero.

Availability: Unix, Windows

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

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, andresource usage information is returned. Refer toresource.getrusage() for details on resource usage information. Theoption argument is the same as that provided towaitpid() andwait4().

Availability: Unix.

New in version 2.5.

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 same asthose provided towaitpid().

Availability: Unix.

New in version 2.5.

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.

New in version 2.3.

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.

New in version 2.3.

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.

Availability: Unix.

New in version 2.3.

os.WIFCONTINUED(status)

ReturnTrue if the process has been continued from a job control stop,otherwise returnFalse.

Availability: Unix.

New in version 2.3.

os.WIFSTOPPED(status)

ReturnTrue if the process has been stopped, otherwise returnFalse.

Availability: Unix.

os.WIFSIGNALED(status)

ReturnTrue if the process exited due to a signal, otherwise returnFalse.

Availability: Unix.

os.WIFEXITED(status)

ReturnTrue if the process exited using theexit(2) system call,otherwise returnFalse.

Availability: Unix.

os.WEXITSTATUS(status)

IfWIFEXITED(status) is true, return the integer parameter to theexit(2) system call. Otherwise, the return value is meaningless.

Availability: Unix.

os.WSTOPSIG(status)

Return the signal which caused the process to stop.

Availability: Unix.

os.WTERMSIG(status)

Return the signal which caused the process to exit.

Availability: Unix.

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

New in version 2.3.

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.

New in version 2.2.

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.

New in version 2.4.

15.1.7.Miscellaneous Functions

os.urandom(n)

Return a string ofn 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 a UNIX-likesystem this will query/dev/urandom, and on Windows it will useCryptGenRandom(). If a randomness source is not found,NotImplementedError will be raised.

For an easy-to-use interface to the random number generatorprovided by your platform, please seerandom.SystemRandom.

New in version 2.4.