The os System Module

The os module is the primary operating system (OS) services interface. It provides generic OS support and a standard, platform-independent OS interface. The os module includes tools for environments, processes, files, shell commands, and much more. It also includes a nested submodule, os.path, which provides a portable interface to directory processing tools.

Scripts that use os and os.path for systems programming are generally portable across most Python platforms. However, some os exports are not available on all platforms (e.g., fork is available on Unix and Cygwin, but not in the standard Windows version of Python). Because the portability of such calls can change over time, consult the Python Library Reference for platform details.

See also related system modules: glob (filename expansion); tempfile (temporary files); signal (signal handling); socket (networking and IPC); threading (multithreading); queue (thread communication); subprocess (spawned command control); multiprocessing (threading-like API for processes); getopt and optparse (command-line processing); and others.

Administrative Tools

Following are some miscellaneous module-related exports:

error

An alias for the built-in OSError exception. Raised for os module-related errors. 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 in the Python Library Reference for names of the error codes defined by the underlying OS.

When exceptions are classes, this exception carries two attributes: errno, the value of the C errno variable; and strerror, the corresponding error message from strerror(). For exceptions that involve a file pathname (e.g., chdir(), unlink()), the exception instance also contains the attribute filename, the filename passed in.

name

Name of OS-specific modules whose names are copied to the top level of os (e.g., posix, nt, mac, os2, ce, or java). See also platform in the section The sys Module.

path

Nested module for portable pathname-based utilities. For example, os.path.split is a platform-independent directory name tool that internally uses an appropriate platform-specific call.

Portability Constants

This section describes tools for parsing and building directory and search path strings portably. They are automatically set to the appropriate value for the platform on which a script is running.

curdir

String used to represent current directory (e.g., . for Windows and POSIX, : for Macintosh).

pardir

String used to represent parent directory (e.g., .. for POSIX, :: for Macintosh).

sep

String used to separate directories (e.g., / for Unix, for Windows, or : for Macintosh).

altsep

Alternative separator string or None (e.g., / for Windows).

extsep

The character that separates the base filename from the extension (e.g., .).

pathsep

Character used to separate search path components, as in the PATH and PYTHONPATH shell variable settings (e.g., ; for Windows, : for Unix).

defpath

Default search path used by os.exec*p* calls if there is no PATH setting in the shell.

linesep

String used to terminate lines on current platform (e.g., for POSIX, for Mac OS, and for Windows). Do not use this when writing lines in text mode files—use the autotranslation of ' '.

Shell Commands

These functions run programs in the underlying operating system. In Python 2.X, this module has os.popen2/3/4 calls, which have been replaced by subprocess.Popen in Python 3.0.

system(cmd)

Executes a command string cmd in a subshell process. Returns the exit status of the spawned process. Unlike popen, does not connect to cmd’s standard streams via pipes. Hints: add an & at the end of cmd to run the command in the background on Unix (e.g., os.system('python main.py &')); use a DOS start command to launch programs easily on Windows (e.g., os.system('start file.html')).

startfile(filepathname)

Starts a file with its associated application. Acts like double-clicking the file in Windows Explorer or giving the filename as an argument to a DOS start command (e.g., with os.system('start path')). The file is opened in the application with which its extension is associated; the call does not wait, and does not generally pop up a DOS console window. Windows only, new in version 2.0.

popen(cmd, mode='r', buffering=None)

Opens a pipe to or from the shell command string cmd, to send or capture data. Returns an open file object, which can be used to either read from cmd’s standard output stream stdout (mode 'r') or write to cmd’s standard input stream stdin (mode 'w'). For example, dirlist = os.popen('ls −l *.py').read() reads the output of a Unix ls command.

cmd is any command string you can type at your system’s console or shell prompt. mode can be 'r' or 'w' and defaults to 'r'. buffering is the same as in the built-in open function. cmd runs independently; its exit status is returned by the resulting file object’s close method, except that None is returned if exit status is 0 (no errors). Use readline() or iteration to read output line by line.

Python 2.X also has variants popen2, popen3, and popen4 to connect to other streams of the spawned command (e.g., popen2 returns a tuple (child_stdin, child_stdout)). In Python 3.0, these calls are removed; use subprocess.Popen() instead. The subprocess module in version 2.4 and later allows scripts to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. See the Python Library Reference.

spawn*(args...)

A family of functions for spawning programs and commands. See Process Control, as well as the Python Library Reference for more details. The subprocess module is a generally preferred alternative to these calls.

Environment Tools

These attributes export execution environment and context.

environ

The shell environment variable dictionary-like object. os.environ['USER'] is the value of variable USER in the shell (equivalent to $USER in Unix and %USER% in DOS). Initialized on program start-up. Changes made to os.environ by key assignment are exported outside Python using a call to C’s putenv and are inherited by any processes that are later spawned in any way, as well as any linked-in C code.

putenv(varname, value)

Sets the shell environment variable named varname to the string value. Affects subprocesses started with system, popen, spawnv, or fork and execv. Assignment to os.environ keys automatically calls putenv (but putenv calls don’t update environ).

getcwd()

Returns the current working directory name as a string.

chdir(path)

Changes the current working directory for this process to path, a directory name string. Future file operations are relative to the new current working directory.

strerror(code)

Returns an error message corresponding to code.

times()

Returns a five-tuple containing elapsed CPU time information for the calling process in floating-point seconds: (user-time, system-time, child-user-time, child-system-time, elapsed-real-time). Also see the section The time Module.

umask(mask)

Sets the numeric umask to mask and returns the prior value.

uname()

Returns OS name tuple of strings: (systemname, nodename, release, version, machine).

File Descriptor Tools

The following functions process files by their descriptors (fd is a file-descriptor integer). os module descriptor-based files are meant for low-level file tasks and are not the same as stdio file objects returned by the built-in open() function (though os.fdopen and the file object fileno method convert between the two). File objects, not descriptors, should normally be used for most file processing.

close(fd)

Closes file descriptor fd (not a file object).

dup(fd)

Returns duplicate of file descriptor fd.

dup2(fd, fd2)

Copies file descriptor fd to fd2 (close fd2 first if open).

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

Returns a built-in file object (stdio) connected to file descriptor fd (an integer). mode and bufsize have the same meaning as in the built-in open() function (see the section Built-in Functions). A conversion from descriptor-based files to file objects is normally created by the built-in open() function. Hint: use fileobj.fileno to convert a file object to a descriptor.

fstat(fd)

Returns status for file descriptor fd (like stat).

ftruncate(fd, length)

Truncates the file corresponding to file descriptor fd so that it is at most length bytes in size.

isatty(fd)

Returns 1 if file descriptor fd is open and connected to a tty(-like) device.

lseek(fd, pos, how)

Sets the current position of file descriptor fd to pos (for random access). how can be 0 to set the position relative to the start of the file, 1 to set it relative to the current position, or 2 to set it relative to the end.

open(filename, flags [, mode])

Opens a file descriptor-based file and returns the file descriptor (an integer, not an stdio file object). Intended for low-level file tasks only; not the same as the built-in open() function. mode defaults to 0777 (octal), and the current umask value is first masked out. flag is a bitmask: use | to combine both platform-neutral and platform-specific flag constants defined in the os module (see Table 1-18).

pipe()

See the section Process Control.

read(fd, n)

Reads at most n bytes from file descriptor fd and returns those bytes as a string.

write(fd, str)

Writes all bytes in string str to file descriptor fd.

Table 1-18. Sample or-able flags for os.open

O_APPEND

O_EXCL

O_RDONLY

O_TRUNC

O_BINARY

O_NDELAY

O_RDWR

O_WRONLY

O_CREAT

O_NOCTTY

O_RSYNC

 

O_DSYNC

O_NONBLOCK

O_SYNC

 

File Pathname Tools

The following functions process files by their pathnames (path is a string pathname of a file). See also the section The os.path Module. In Python 2.X, this module also includes temporary file tools that have been replaced with the tempfile module in Python 3.0.

chdir(path)
getcwd()

See the section Environment Tools.

chmod(path, mode)

Changes mode of file path to numeric mode.

chown(path, uid, gid)

Changes owner/group IDs of path to numeric uid/gid.

link(srcpath, dstpath)

Creates a hard link to file src, named dst.

listdir(path)

Returns a list of names of all the entries in the directory path. A fast and portable alternative to the glob module and to running shell listing commands with os.popen. See also module glob for filename expansion. In 3.X, passed and returns bytes instead of str to suppress Unicode filename decoding per platform default (also for glob, os.walk).

lstat(path)

Like stat, but does not follow symbolic links.

mkfifo(path [, mode])

Creates a FIFO (a named pipe) identified by string path with access permission given by numeric mode (but does not open it). The default mode is 0666 (octal). The current umask value is first masked out from the mode. FIFOs are pipes that live in the filesystem and can be opened and processed like regular files. FIFOs exist until deleted.

mkdir(path [, mode])

Makes a directory called path, with the given mode. The default mode is 777 (octal).

makedirs(path [, mode])

Recursive directory-creation function. Like mkdir, but makes all intermediate-level directories needed to contain the leaf directory. Throws an exception if the leaf directory already exists or cannot be created. mode defaults to 0777 (octal).

readlink(path)

Returns the path referenced by a symbolic link path.

remove(path)
unlink(path)

Removes (deletes) the file named path. remove is identical to unlink. See rmdir and removedirs, discussed in this list, for removing directories.

removedirs(path)

Recursive directory-removal function. Similar to rmdir, but if the leaf directory is successfully removed, then directories corresponding to the rightmost path segments will be pruned away until either the whole path is consumed or an error is raised. Throws an exception if the leaf directory could not be removed.

rename(srcpath, dstpath)

Renames (moves) file src to name dst.

renames(oldpath, newpath)

Recursive directory- or file-renaming function. Like rename, but creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to the rightmost path segments of the old name will be pruned away using removedirs.

rmdir(path)

Removes (deletes) a directory named path.

stat(path)

Runs stat system call for path; returns a tuple of integers with low-level file information (whose items are defined and processed by tools in module stat).

symlink(srcpath, dstpath)

Creates a symbolic link to file src, called dst.

utime(path, (atime, mtime))

Sets file path access and modification times.

access(path, mode)

Consult the Python Library Reference or Unix manpages for details.

walk(top [, topdown=True [, onerror=None] [, followlinks=False]]])

Generates the filenames in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), yields a three-tuple (dirpath, dirnames, filenames). dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding . and ..). filenames is a list of the names of the nondirectory files in dirpath. Note that the names in the lists do not contain path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

If optional argument topdown is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is false, the triple for a directory is generated after the triples for all its subdirectories (directories are generated bottom-up). If optional onerror is specified, it should be a function, which will be called with one argument, an os.error instance. By default, will not walk down into symbolic links that resolve to directories; set followlinks to True to visit directories pointed to by symlinks, on systems that support them.

Python 2.X also provides an os.path.walk() call with similar tree-walking functionality, using an event-handler function callback instead of a generator. In Python 3.0, os.path.walk() is removed due to its redundancy; use os.walk() instead. See also module glob for filename expansion.

Process Control

The following functions are used to create and manage processes and programs. Refer also to the section Shell Commands for other ways to start programs and files.

abort()

Sends a SIGABRT signal to the current process. On Unix, the default behavior is to produce a core dump; on Windows, the process immediately returns exit code 3.

execl(path, arg0, arg1,...)

Equivalent to execv(path, (arg0, arg1,...)).

execle(path, arg0, arg1,..., env)

Equivalent to execve(path, (arg0, arg1,...), env).

execlp(path, arg0, arg1,...)

Equivalent to execvp(path, (arg0, arg1,...)).

execve(path, args, env)

Like execv, but the env dictionary replaces the shell variable environment. env must map strings to strings.

execvp(path, args)

Like execv(path, args), but duplicates the shell’s actions in searching for an executable file in a list of directories. The directory list is obtained from os.environ['PATH'].

execvpe(path, args, env)

A cross between execve and execvp. The directory list is obtained from os.environ['PATH'].

execv(path, args)

Executes the executable file path with the command-line argument args, replacing the current program in this process (the Python interpreter). args can be a tuple or a list of strings, and it starts with the executable’s name by convention (argv[0]). This function call never returns, unless an error occurs while starting the new program.

_exit(n)

Exits the process immediately with status n, without performing cleanup. Normally used only in a child process after a fork; the standard way to exit is to call sys.exit(n).

fork()

Spawns a child process (a virtual copy of the calling process, running in parallel); returns 0 in the child and the new child’s process ID in the parent. Not available in standard Windows Python, but is available on Windows in Cygwin Python.

getpid()
getppid()

Returns the process ID of the current (calling) process; getppid() returns the parent process ID.

getuid()
geteuid()

Returns the process’s user ID; geteuid returns the effective user ID.

kill(pid, sig)

Kills the process with ID pid by sending signal sig. See also the signal module for register signal handlers.

mkfifo(path [, mode])

See the section File Pathname Tools (files used for process synchronization).

nice(increment)

Adds increment to process’s “niceness” (i.e., lowers its CPU priority).

pipe()

Returns a tuple of file descriptors (rfd, wfd) for reading and writing a new anonymous (unnamed) pipe. Used for cross-process communication.

plock(op)

Locks program segments into memory. op (defined in <sys./lock.h>) determines which segments are locked.

spawnv(mode, path, args)

Executes program path in a new process, passing the arguments specified in args as a command line. args can be a list or a tuple. mode is a magic operational constant made from the following names: P_WAIT, P_NOWAIT, P_NOWAITO, P_OVERLAY, and P_DETACH. On Windows, roughly equivalent to a fork+execv combination (fork is not yet available on standard Windows Python, though popen and system are). See also the subprocess module for more powerful alternatives.

spawnve(mode, path, args, env)

Like spawnv, but passes the contents of mapping env as the spawned program’s shell environment.

wait()

Waits for completion of a child process. Returns a tuple with child’s ID and exit status.

waitpid(pid, options)

Waits for child process with ID pid to complete. options is 0 for normal use, or os.WNOHANG to avoid hanging if no child status is available. If pid is 0, the request applies to any child in the process group of the current process. See also the process exit status-check functions documented in the Python Library Reference (e.g., WEXITSTATUS(status) to extract the exit code).

The os.path Module

The os.path module provides additional file directory pathname-related services and portability tools. This is a nested module: its names are nested in the os module within the submodule os.path (e.g., the exists function is obtained by importing os and using os.path.exists).

Most functions in this module take an argument path, the string directory pathname of a file (e.g., "C:dir1spam.txt"). Directory paths are generally coded per the platform’s conventions and are mapped to the current working directory if lacking a directory prefix. Hint: forward slashes usually work as directory separators on all platforms. In Python 2.X, this module includes an os.path.walk tool, which has been replaced by os.walk in Python 3.0.

abspath(path)

Returns a normalized absolute version of path. On most platforms, this is equivalent to normpath(join(os.getcwd(), path)).

basename(path)

Same as second half of pair returned by split(path).

commonprefix(list)

Returns longest path prefix (character by character) that is a prefix of all paths in list.

dirname(path)

Same as first half of pair returned by split(path).

exists(path)

True if string path is the name of an existing file path.

expanduser(path)

Returns string that is path with embedded ˜ username expansion done.

expandvars(path)

Returns string that is path with embedded $ environment variables expanded.

getatime(path)

Returns time of last access of path (seconds since the epoch).

getmtime(path)

Returns time of last modification of path (seconds since the epoch).

getsize(path)

Returns size, in bytes, of file path.

isabs(path)

True if string path is an absolute path.

isfile(path)

True if string path is a regular file.

isdir(path)

True if string path is a directory.

islink(path)

True if string path is a symbolic link.

ismount(path)

True if string path is a mount point.

join(path1 [, path2 [, ...]])

Joins one or more path components intelligently (using platform-specific separator conventions between each part).

normcase(path)

Normalizes case of a pathname. Has no effect on Unix; on case-insensitive filesystems, converts to lowercase; on Windows, also converts / to .

normpath(path)

Normalizes a pathname. Collapses redundant separators and up-level references; on Windows, converts / to .

realpath(path)

Returns the canonical path of the specified filename, eliminating any symbolic links encountered in the path.

samefile(path1, path2)

Returns true if both pathname arguments refer to the same file or directory.

sameopenfile(fp1, fp2)

Returns true if both file objects refer to the same file.

samestat(stat1, stat2)

Returns true if both stat tuples refer to the same file.

split(path)

Splits path into (head, tail), where tail is the last pathname component and head is everything leading up to tail. Same as tuple (dirname(path), basename(path)).

splitdrive(path)

Splits path into a pair ('drive:', tail) (on Windows).

splitext(path)

Splits path into (root, ext), where the last component of root contains no ., and ext is empty or starts with a ..

walk(path, visitor, data)

An alternative to os.walk in Python 2.X only. Removed in Python 3.0: use os.walk, not os.path.walk.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset