Cover | Table of Contents | Colophon
|
Features
|
Benefits
|
|---|---|
|
No manual compile or link steps
|
Rapid development cycle turnaround
|
|
No type declarations
|
Simpler, shorter, and more flexible programs
|
|
Automatic memory management
|
Garbage collection avoids bookkeeping code and errors
|
|
High-level datatypes and operations
|
Fast development using built-in object types
|
|
Object-oriented programming
|
Code reuse; C++, Java, COM, and .NET integration
|
|
Embedding and extending in C
|
Optimization, customization, legacy code, system "glue"
|
|
Classes, modules, exceptions
|
Modular "programming-in-the-large" support for large-scale projects
|
|
A simple, clear syntax and design
|
Readability, maintainability, ease of learning, less potential for bugs
|
>>> characters are Python's prompt—if you've never run Python code this way before, see an introductory resource such as O'Reilly's Learning Python for help with getting started):>>>bob = ['Bob Smith', 42, 30000, 'software'] >>> sue = ['Sue Jones', 45, 40000, 'music']
>>>bob[0], sue[2] # fetch name, pay
('Bob Smith', 40000)>>>bob[0].split( )[-1] # what's bob's last name? 'Smith' >>> sue[2] *= 1.25 # give sue a 25% raise >>> sue ['Sue Jones', 45, 50000.0, 'music']
>>>import shelve >>> db = shelve.open('people-shelve') >>> bob = db['bob'] >>> bob['name'].split( )[-1] # get bob's last name 'Smith' >>> sue = db['sue'] >>> sue['pay'] *= 1.25 # give sue a raise >>> sue['pay'] 75000.0 >>> db['sue'] = sue >>> db.close( )
# interactive queries
import shelve
fieldnames = ('name', 'age', 'job', 'pay')
maxfield = max(len(f) for f in fieldnames)
db = shelve.open('class-shelve')
while True:
key = raw_input('\nKey? => ') # key or empty line, exc at eof
if not key: break
try:
record = db[key] # fetch by key, show in console
except:
print 'No such key "%s"!' % key
else:
for field in fieldnames:
print field.ljust(maxfield), '=>', getattr(record, field)getattr to fetch an object's attribute when given its name string, and the ljust left-justify method of strings to align outputs (maxfield, derived from a comprehension expression, is the length of the longest field name). When run, this script goes into a loop, inputting keys from the interactive user (technically, from the standard input stream, which is usually a console window) and displaying the fetched records field by field. An empty line ends the session:Key? =>sue name => Sue Jones age => 45 job => music pay => 40000 Key? => nobody No such key "nobody"! Key? =>
from Tkinter import * Label(text='Spam').pack( ) mainloop( )
Label, geometry manager methods such as pack, widget configuration constants such as TOP and RIGHT side hints for pack, and the mainloop call, which starts event processing.
sys and os modules in the first few sections of this chapter before moving on to larger system programming concepts. As you can tell from the length of their attribute lists, both of these are large modules (their content may vary slightly per Python version and platform):>>>import sys, os >>> len(dir(sys)) # 56 attributes 56 >>> len(dir(os)) # 118 on Windows, more on Unix 118 >>> len(dir(os.path)) # a nested module within os 43
sys
and os.
That's somewhat oversimplified; other standard modules belong to this domain too. Among them are the following:glob
socket
thread
and
queue
time
fcntl
open). But sys and os together form the core of Python's system tools arsenal.sys exports components related to the Python interpreter itself (e.g., the module search path), and os contains variables and functions that map to the operating system on which Python is run. In practice, this distinction may not always seem clear-cut (e.g., the standard input and output streams show up in sys, but they are arguably tied to operating system paradigms). The good news is that you'll soon use the tools in these modules so often that their locations will be permanently stamped on your memory.
sys and os modules form the core of much of Python's system-related tool set. Let's now take a quick, interactive tour through some of the tools in these two modules before applying them in bigger examples. We'll start with sys, the smaller of the two; remember that to see a full list of all the attributes in sys, you need to pass it to the dir function (or see where we did so earlier in this chapter).sys includes both informational names and functions that take action. For instance, its attributes give us the name of the underlying operating system on which the platform code is running, the largest possible integer on this machine, and the version number of the Python interpreter running our code:C:\...\PP3E\System>python >>> import sys >>> sys.platform, sys.maxint, sys.version ('win32', 2147483647, '2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)]') >>> >>> if sys.platform[:3] == 'win': print 'hello windows' ... hello windows
sys.platform string as done here; although most of Python is cross-platform, nonportable tools are usually wrapped in if tests like the one here. For instance, we'll see later that today's program launch and low-level console interaction tools vary per platform—simply test sys.platform to pick the right tool for the machine on which your script is running.sys module also lets us inspect the module search path
both interactively and within a Python program. sys.path is a list of strings representing the true search path in a running Python interpreter. When a module is imported, Python scans this list from left to right, searching for the module's file on each directory named in the list. Because of that, this is the place to look to verify that your search path is really set as intended.
sys.path list is simply initialized from your PYTHONPATH setting—the content of any .pth path files located in Python's directories on your machine plus system defaults—when the interpreter is first started up. In fact, if you inspect os is the larger of the two core system modules. It contains all of the usual operating-system calls you may have used in your 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.os module's source code, you'll notice that it really just imports whatever platform-specific system module you have on your computer (e.g., nt, mac, posix). See the os.py file in the Python source library directory—it simply runs a from* statement to copy all names out of a platform-specific module. By always importing os rather than platform-specific modules, though, your scripts are mostly immune to platform implementation differences. 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 it is technically feasible.os. As a preview, Table 3-1 summarizes some of the most commonly used tools in the os module organized by functional area.|
Tasks
|
Tools
|
|---|---|
|
Shell variables
|
os.environ
|
|
Running programs
|
os.system, os.popen, os.popen2/3/4, os.startfile
|
os.getcwd gives access to the directory from which a script is started, and many file tools use its value implicitly.sys.argv gives access to words typed on the command line that are used to start the program and that serve as script inputs.os.environ provides an interface to names assigned in the enclosing shell (or a parent program) and passed in to the script.sys.stdin, stdout, and stderr export the three input/output streams that are at the heart of command-line shell tools.