[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Other sys Module Exports


The sys module exports additional commonly-used tools that we will meet in the con-
text of larger topics and examples introduced later in this part of the book. For instance:



  • Command-line arguments show up as a list of strings called sys.argv.

  • Standard streams are available as sys.stdin, sys.stdout, and sys.stderr.

  • Program exit can be forced with sys.exit calls.


Since these lead us to bigger topics, though, we will cover them in sections of their own.


Introducing the os Module


As mentioned, os is the larger of the two core system modules. It contains all of the
usual operating-system calls you use in C programs and shell scripts. Its calls deal with
directories, processes, shell variables, and the like. Technically, this module provides
POSIX tools—a portable standard for operating-system calls—along with platform-
independent directory processing tools as the nested module os.path. Operationally,
os serves as a largely portable interface to your computer’s system calls: scripts written
with os and os.path can usually be run unchanged on any platform. On some platforms,
os includes extra tools available just for that platform (e.g., low-level process calls on
Unix); by and large, though, it is as cross-platform as is technically feasible.


Tools in the os Module


Let’s take a quick look at the basic interfaces in os. As a preview, Table 2-1 summarizes
some of the most commonly used tools in the os module, organized by functional area.


Table 2-1. Commonly used os module tools


Tasks Tools
Shell variables os.environ
Running programs os.system, os.popen, os.execv, os.spawnv
Spawning processes os.fork, os.pipe, os.waitpid, os.kill
Descriptor files, locks os.open, os.read, os.write
File processing os.remove, os.rename, os.mkfifo, os.mkdir, os.rmdir
Administrative tools os.getcwd, os.chdir, os.chmod, os.getpid, os.listdir, os.access
Portability tools os.sep, os.pathsep, os.curdir, os.path.split, os.path.join
Pathname tools os.path.exists('path'), os.path.isdir('path'), os.path.getsize('path')

If you inspect this module’s attributes interactively, you get a huge list of names that
will vary per Python release, will likely vary per platform, and isn’t incredibly useful


90 | Chapter 2: System Tools

Free download pdf