8.1 Built-in Module posix

This module provides access to operating system functionality that is standardized by the C Standard and the POSIX standard (a thinly disguised Unix interface).

Do not import this module directly. Instead, import the module os, which provides a portable version of this interface. On Unix, the os module provides a superset of the posix interface. On non-Unix operating systems the posix module is not available, but a subset is always available through the os interface. Once os is imported, there is no performance penalty in using it instead of posix. In addition, os provides some additional functionality, such as automatically calling putenv() when an entry in os.environ is changed.

The descriptions below are very terse; refer to the corresponding Unix manual (or POSIX documentation) entry for more information. Arguments called path refer to a pathname given as a string.

Errors are reported as exceptions; the usual exceptions are given for type errors, while errors reported by the system calls raise error (a synonym for the standard exception OSError), described below.

Module posix defines the following data items:

environ
A dictionary representing the string environment at the time the interpreter was started. For example, posix.environ['HOME'] is the pathname of your home directory, equivalent to getenv("HOME") in C.

Modifying this dictionary does not affect the string environment passed on by execv(), popen() or system(); if you need to change the environment, pass environ to execve() or add variable assignments and export statements to the command string for system() or popen().

However: If you are using this module via the os module (as you should - see the introduction above), environ is a a mapping object that behaves almost like a dictionary but invokes putenv() automatically called whenever an item is changed.

error
This exception is raised when a POSIX function returns a POSIX-related error (e.g., not for illegal argument types). The accompanying value is a pair containing the numeric error code from errno and the corresponding string, as would be printed by the C function perror(). See the module errno, which contains names for the error codes defined by the underlying operating system.

When exceptions are classes, this exception carries two attributes, errno and strerror. The first holds the value of the C errno variable, and the latter holds the corresponding error message from strerror(). For exceptions that involve a file system path (e.g. chdir or unlink), the exception instance will contain a third attribute filename which is the file name passed to the function.

When exceptions are strings, the string for the exception is 'OSError'.

It defines the following functions and constants:

chdir (path)
Change the current working directory to path.

chmod (path, mode)
Change the mode of path to the numeric mode.

chown (path, uid, gid)
Change the owner and group id of path to the numeric uid and gid. (Not on MS-DOS.)

close (fd)
Close file descriptor fd.

Note: this function is intended for low-level I/O and must be applied to a file descriptor as returned by open() or pipe(). To close a ``file object'' returned by the built-in function open() or by popen() or fdopen(), use its close() method.

dup (fd)
Return a duplicate of file descriptor fd.

dup2 (fd, fd2)
Duplicate file descriptor fd to fd2, closing the latter first if necessary.

execv (path, args)
Execute the executable path with argument list args, replacing the current process (i.e., the Python interpreter). The argument list may be a tuple or list of strings. (Not on MS-DOS.)

execve (path, args, env)
Execute the executable path with argument list args, and environment env, replacing the current process (i.e., the Python interpreter). The argument list may be a tuple or list of strings. The environment must be a dictionary mapping strings to strings. (Not on MS-DOS.)

_exit (n)
Exit to the system with status n, without calling cleanup handlers, flushing stdio buffers, etc. (Not on MS-DOS.)

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

fdopen (fd[, mode[, bufsize]])
Return an open file object connected to the file descriptor fd. The mode and bufsize arguments have the same meaning as the corresponding arguments to the built-in open() function.

fork ()
Fork a child process. Return 0 in the child, the child's process id in the parent. (Not on MS-DOS.)

fstat (fd)
Return status for file descriptor fd, like stat().

ftruncate (fd, length)
Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size.

getcwd ()
Return a string representing the current working directory.

getegid ()
Return the current process' effective group id. (Not on MS-DOS.)

geteuid ()
Return the current process' effective user id. (Not on MS-DOS.)

getgid ()
Return the current process' group id. (Not on MS-DOS.)

getpgrp ()
Return the current process group id. (Not on MS-DOS.)

getpid ()
Return the current process id. (Not on MS-DOS.)

getppid ()
Return the parent's process id. (Not on MS-DOS.)

getuid ()
Return the current process' user id. (Not on MS-DOS.)

kill (pid, sig)
Kill the process pid with signal sig. (Not on MS-DOS.)

link (src, dst)
Create a hard link pointing to src named dst. (Not on MS-DOS.)

listdir (path)
Return a list containing the names of the entries in the directory. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

lseek (fd, pos, how)
Set the current position of file descriptor fd to position pos, modified by how: 0 to set the position relative to the beginning of the file; 1 to set it relative to the current position; 2 to set it relative to the end of the file.

lstat (path)
Like stat(), but do not follow symbolic links. (On systems without symbolic links, this is identical to stat().)

mkfifo (path[, mode])
Create a FIFO (a POSIX named pipe) named path with numeric mode mode. The default mode is 0666 (octal). The current umask value is first masked out from the mode. (Not on MS-DOS.)

FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with os.unlink()). Generally, FIFOs are used as rendezvous between ``client'' and ``server'' type processes: the server opens the FIFO for reading, and the client opens it for writing. Note that mkfifo() doesn't open the FIFO -- it just creates the rendezvous point.

mkdir (path[, mode])
Create a directory named path with numeric mode mode. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.

nice (increment)
Add increment to the process' ``niceness''. Return the new niceness. (Not on MS-DOS.)

open (file, flags[, mode])
Open the file file and set various flags according to flags and possibly its mode according to mode. The default mode is 0777 (octal), and the current umask value is first masked out. Return the file descriptor for the newly opened file.

For a description of the flag and mode values, see the Unix or C run-time documentation; flag constants (like O_RDONLY and O_WRONLY) are defined in this module too (see below).

Note: this function is intended for low-level I/O. For normal usage, use the built-in function open(), which returns a ``file object'' with read() and write() methods (and many more).

pipe ()
Create a pipe. Return a pair of file descriptors (r, w) usable for reading and writing, respectively. (Not on MS-DOS.)

plock (op)
Lock program segments into memory. The value of op (defined in <sys/lock.h>) determines which segments are locked. (Not on MS-DOS.)

popen (command[, mode[, bufsize]])
Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as the corresponding argument to the built-in open() function. The exit status of the command (encoded in the format specified for wait()) is available as the return value of the close() method of the file object. (Not on MS-DOS.)

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

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

strerror (code)
Return the error message corresponding to the error code in code.

read (fd, n)
Read at most n bytes from file descriptor fd. Return a string containing the bytes read.

Note: this function is intended for low-level I/O and must be applied to a file descriptor as returned by open() or pipe(). To read a ``file object'' returned by the built-in function open() or by popen() or fdopen(), or sys.stdin, use its read() or readline() methods.

readlink (path)
Return a string representing the path to which the symbolic link points. (On systems without symbolic links, this always raises error.)

remove (path)
Remove the file path. See rmdir() below to remove a directory. This is identical to the unlink() function documented below.

rename (src, dst)
Rename the file or directory src to dst.

rmdir (path)
Remove the directory path.

setgid (gid)
Set the current process' group id. (Not on MS-DOS.)

setpgrp ()
Calls the system call setpgrp() or setpgrp(0, 0) depending on which version is implemented (if any). See the Unix manual for the semantics. (Not on MS-DOS.)

setpgid (pid, pgrp)
Calls the system call setpgid(). See the Unix manual for the semantics. (Not on MS-DOS.)

setsid ()
Calls the system call setsid(). See the Unix manual for the semantics. (Not on MS-DOS.)

setuid (uid)
Set the current process' user id. (Not on MS-DOS.)

stat (path)
Perform a stat() system call on the given path. The return value is a tuple of at least 10 integers giving the most important (and portable) members of the stat structure, in the order st_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. (On MS-DOS, some items are filled with dummy values.)

Note: The standard module stat defines functions and constants that are useful for extracting information from a stat structure.

symlink (src, dst)
Create a symbolic link pointing to src named dst. (On systems without symbolic links, this always raises error.)

system (command)
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to posix.environ, sys.stdin etc. are not reflected in the environment of the executed command. The return value is the exit status of the process encoded in the format specified for wait().

tcgetpgrp (fd)
Return the process group associated with the terminal given by fd (an open file descriptor as returned by open()). (Not on MS-DOS.)

tcsetpgrp (fd, pg)
Set the process group associated with the terminal given by fd (an open file descriptor as returned by open()) to pg. (Not on MS-DOS.)

times ()
Return a 5-tuple of floating point numbers indicating accumulated (CPU or other) times, in seconds. The items are: user time, system time, children's user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2). (Not on MS-DOS.)

umask (mask)
Set the current numeric umask and returns the previous umask. (Not on MS-DOS.)

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

unlink (path)
Remove the file path. This is the same function as remove; the unlink name is its traditional Unix name.

utime (path, (atime, mtime ))
Set the access and modified time of the file to the given values. (The second argument is a tuple of two items.)

wait ()
Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. (Not on MS-DOS.)

waitpid (pid, options)
Wait for completion of a child process given by proces id, and return a tuple containing its pid and exit status indication (encoded as for wait()). The semantics of the call are affected by the value of the integer options, which should be 0 for normal operation. (If the system does not support waitpid(), this always raises error. Not on MS-DOS.)

write (fd, str)
Write the string str to file descriptor fd. Return the number of bytes actually written.

Note: this function is intended for low-level I/O and must be applied to a file descriptor as returned by open() or pipe(). To write a ``file object'' returned by the built-in function open() or by popen() or fdopen(), or sys.stdout or sys.stderr, use its write() method.

WNOHANG
The option for waitpid() to avoid hanging if no child process status is available immediately.

O_RDONLY
O_WRONLY
O_RDWR
O_NDELAY
O_NONBLOCK
O_APPEND
O_DSYNC
O_RSYNC
O_SYNC
O_NOCTTY
O_CREAT
O_EXCL
O_TRUNC
Options for the flag argument to the open() function. These can be bit-wise OR'd together.