Text
stringlengths
1
9.41k
You’ll only need to do this once per machine, and if you will be running a frozen binary (described in Chapter 2) or self-installing system, you may not need to do much more. ###### Is Python Already Present? Before you do anything else, check whether you already have a recent Python on your machine.
If you are working on Linux, Mac OS X, or some Unix systems, Python is probably already installed on your computer, though it may be one or two releases behind the cutting edge.
Here’s how to check: - On Windows, check whether there is a Python entry in the Start button’s All Programs menu (at the bottom left of the screen). - On Mac OS X, open a Terminal window (Applications→Utilities→Terminal) and type python at the prompt. - On Linux and Unix, type python at a shell prompt (a.k.a.
terminal window), and see what happens. Alternatively, try searching for “python” in the usual places—/usr/bin, /usr/local/bin, etc. If you find a Python, make sure it’s a recent version.
Although any recent Python will do for most of this text, this edition focuses on Python 3.0 and 2.6 specifically, so you may want to install one of these to run some of the examples in this book. ----- Speaking of versions, I recommend starting out with Python 3.0 or later if you’re learning Python anew and don’t n...
Some popular Python-based systems still use older releases, though (2.5 is still widespread), so if you’re working with existing systems be sure to use a version relevant to your needs; the next section describes locations where you can fetch a variety of Python versions. ###### Where to Get Python If there is no Pyt...
The good news is that Python is an open source system that is freely available on the Web and very easy to install on most platforms. You can always fetch the latest and greatest standard Python release from http://www _.python.org, Python’s official website.
Look for the Downloads link on that page, and_ choose a release for the platform on which you will be working.
You’ll find prebuilt self-installer files for Windows (run to install), Installer Disk Images for Mac OS X (installed per Mac conventions), the full source code distribution (typically compiled on Linux, Unix, or OS X machines to generate an interpreter), and more. Although Python is standard on Linux these days, you ...
Python’s website also has links to pages where versions for other platforms are maintained, either at Python.org itself or offsite. A Google web search is another great way to find Python packages.
Among other platforms, you can find Python pre-built for iPods, Palm handhelds, Nokia cell phones, PlayStation and PSP, Solaris, AS/400, and Windows Mobile. If you find yourself pining for a Unix environment on a Windows machine, you might also be interested in installing Cygwin and its version of Python (see http://w...
Cygwin is a GPL-licensed library and toolset that provides full Unix functionality_ on Windows machines, and it includes a prebuilt Python that makes use of the all the Unix tools provided. You can also find Python on CD-ROMs supplied with Linux distributions, included with some products and computer systems, and encl...
These tend to lag behind the current release somewhat, but usually not seriously so. In addition, you can find Python in some free and commercial development bundles. For example, ActiveState distributes Python as part of its ActivePython, a package that combines standard Python with extensions for Windows development...
Python can also be had today in the Enthought Python Distribution— a package aimed at scientific computing needs—as well as in Portable Python, preconfigured to run directly from a portable device.
Search the Web for details. **|** **f** ----- Finally, if you are interested in alternative Python implementations, run a web search to check out Jython (the Python port to the Java environment) and IronPython (Python for the C#/.NET world), both of which are described in Chapter 2.
Installation of these systems is beyond the scope of this book. ###### Installation Steps Once you’ve downloaded Python, you need to install it.
Installation steps are very platform-specific, but here are a few pointers for the major Python platforms: _Windows_ On Windows, Python comes as a self-installer MSI program file—simply doubleclick on its file icon, and answer Yes or Next at every prompt to perform a default install.
The default install includes Python’s documentation set and support for ``` tkinter (Tkinter in Python 2.6) GUIs, shelve databases, and the IDLE development ``` GUI.
Python 3.0 and 2.6 are normally installed in the directories C:\Python30 and _C:\Python26, though this can be changed at install time._ For convenience, after the install Python shows up in the Start button’s All Programs menu.
Python’s menu there has five entries that give quick access to common tasks: starting the IDLE user interface, reading module documentation, starting an interactive session, reading Python’s standard manuals in a web browser, and uninstalling.
Most of these options involve concepts explored in detail elsewhere in this text. When installed on Windows, Python also by default automatically registers itself to be the program that opens Python files when their icons are clicked (a program launch technique described in Chapter 3).
It is also possible to build Python from its source code on Windows, but this is not commonly done. One note for Windows Vista users: security features of the some versions of Vista change some of the rules for using MSI installer files.
Although this may be a nonissue by the time you read these words, see the sidebar “The Python MSI Installer on Windows Vista” on page 1092 in this appendix for assistance if the current Python installer does not work, or does not place Python in the correct place on your machine. _Linux_ On Linux, Python is available a...
Depending on which RPMs you download, there may be one for Python itself, and another that adds support for ``` tkinter GUIs and the IDLE environment.
Because Linux is a Unix-like system, the ``` next paragraph applies as well. _Unix_ On Unix systems, Python is usually compiled from its full C source code distribution.
This usually only requires you to unpack the file and run simple config and ``` make commands; Python configures its own build procedure automatically, ``` **|** ----- according to the system on which it is being compiled.
However, be sure to see the package’s README file for more details on this process.
Because Python is open source, its source code may be used and distributed free of charge. On other platforms the installation details can differ widely, but they generally follow the platform’s normal conventions.
Installing the “Pippy” port of Python for PalmOS, for example, requires a hotsync operation with your PDA, and Python for the Sharp Zaurus Linux-based PDA comes as one or more .ipk files, which you simply run to install it.
Because additional install procedures for both executable and source forms are well documented, though, we’ll skip further details here. ###### The Python MSI Installer on Windows Vista As I write this, the Python self-installer for Windows is an .msi installation file.
This format works fine on Windows XP (simply double-click on the file, and it runs), but it can have issues on some versions of Windows Vista.
In particular, running the MSI installer by clicking on it may cause Python to be installed at the root of the C: drive, instead of in the correct C:\PythonXX directory.
Python still works in the root directory, but this is not the correct place to install it. This is a Vista security-related issue; in short, MSI files are not true executables, so they do not correctly inherit administrator permissions, even if run by the administrator user.
Instead, MSI files are run via the Windows Registry—their filenames are associated with the MSI installer program. This problem seems to be either Python- or Vista-version specific.
On a recent laptop, for example, Python 2.6 and 3.0 installed without issue.
To install Python 2.5.2 on my Vista-based OQO handheld, though, I had to use a command-line approach to force the required administrator permissions. If Python doesn’t install in the right place for you, here’s the workaround: go to your Start button, select the All Programs entry, choose Accessories, right-click on t...
Now, within the Command Prompt window, issue a cd command to change to the directory where your Python MSI installer file resides (e.g., ``` cd C:\user\downloads), and then run the MSI installer manually by typing a command ``` line of the form msiexec /i python-2.5.1.msi.
Finally, follow the usual GUI interactions to complete the install. Naturally, this behavior may change over time.
This procedure may not be required in every version of Vista, and additional workarounds may be possible (such as disabling Vista security, if you dare).
It’s also possible that the Python self-installer may eventually be provided in a different format that obviates this problem—as a true executable, for instance.
Be sure to try your installer by simply clicking its icon to see if it works properly before attempting any workarounds. **|** **f** ----- ###### Configuring Python After you’ve installed Python, you may want to configure some system settings that impact the way Python runs your code.
(If you are just getting started with the language, you can probably skip this section completely; there is usually no need to specify any system settings for basic programs.) Generally speaking, parts of the Python interpreter’s behavior can be configured with environment variable settings and command-line options.
In this section, we’ll take a brief look at both, but be sure to see other documentation sources for more details on the topics we introduce here. ###### Python Environment Variables Environment variables—known to some as shell variables, or DOS variables—are system-wide settings that live outside Python and thus can...
Python recognizes a handful of environment variable settings, but only a few are used often enough to warrant explanation here.
Table A-1 summarizes the main Python-related environment variable settings. _Table A-1.
Important environment variables_ **Variable** **Role** `PATH (or path)` System shell search path (for finding “python”) `PYTHONPATH` Python module search path (for imports) `PYTHONSTARTUP` Path to Python interactive startup file `TCL_LIBRARY, TK_LIBRARY` GUI extension variables (tkinter) These variables are str...
It should normally include the directory where your Python interpreter lives (the python program on Unix, or the python.exe file on Windows). You don’t need to set this variable at all if you are willing to work in the directory where Python resides, or type the full path to Python in command lines.
On Windows, for instance, the PATH is irrelevant if you run a cd C:\Python30 before running any code (to change to the directory where Python lives), or always type ``` C:\Python30\python instead of just python (giving a full path).
Also, note that PATH settings are mostly for launching programs from command lines; they are ``` usually irrelevant when launching via icon clicks and IDEs. **f** **|** ----- ``` PYTHONPATH ``` The PYTHONPATH setting serves a role similar to PATH: the Python interpreter consults the PYTHONPATH variable to locat...
This list normally includes just your own source code directories.
Its content is merged into the `sys.path` module import search path, along with the script’s directory, any path file settings, and standard library directories. You don’t need to set this variable unless you will be performing cross-directory imports—because Python always searches the home directory of the program’s t...
See also the discussion of .pth path files later in this appendix for an alternative to PYTHONPATH.
For more on the module search path, refer to Chapter 21. ``` PYTHONSTARTUP ``` If PYTHONSTARTUP is set to the pathname of a file of Python code, Python executes the file’s code automatically whenever you start the interactive interpreter, as though you had typed it at the interactive command line.
This is a rarely used but handy way to make sure you always load certain utilities when working interactively; it saves an import. ``` tkinter settings ``` If you wish to use the tkinter GUI toolkit (named Tkinter in 2.6), you might have to set the two GUI variables in the last line of Table A-1 to the names of the so...
However,` these settings are not required on Windows systems (where `tkinter support is` installed alongside Python), and they’re usually not required elsewhere if Tcl and Tk reside in standard directories. Note that because these environment settings are external to Python itself, when you set them is usually irrelev...
The` ``` tkinter module (named Tkinter in 2.6) is a GUI toolkit, and it’s a complete, standard ``` component of Python on Windows and some other platforms.
On some Linux systems, though, the underlying GUI library may not be a standard installed component.
To add GUI support to your Python on Linux if needed, try running a command line of the form yum tkinter to automatically install tkinter’s underlying libraries.
This should work on Linux distributions (and some other systems) on which the yum installation program is available. **|** **f** ----- ###### How to Set Configuration Options The way to set Python-related environment variables, and what to set them to, depends on the type of computer you’re working on.
And again, remember that you won’t necessarily have to set these at all right away; especially if you’re working in IDLE (described in Chapter 3), configuration is not required up front. But suppose, for illustration, that you have generally useful module files in directories called utilities and package1 somewhere on...
That is, to load a file called _spam.py from the utilities directory, you want to be able to say:_ ``` import spam ``` from another file located anywhere on your computer.
To make this work, you’ll have to configure your module search path one way or another to include the directory containing spam.py.
Here are a few tips on this process. ###### Unix/Linux shell variables On Unix systems, the way to set environment variables depends on the shell you use. Under the csh shell, you might add a line like the following in your .cshrc or .login file to set the Python module search path: ``` setenv PYTHONPATH /usr/home/...
Alternatively, if you’re using the ksh shell, the setting might instead appear in your .kshrc file and look like this: ``` export PYTHONPATH="/usr/home/pycode/utilities:/usr/lib/pycode/package1" ``` Other shells may use different (but analogous) syntax. ###### DOS variables (Windows) If you are using MS-DOS, or so...
The configuration command on such machines has a syntax unique to DOS: ``` set PYTHONPATH=c:\pycode\utilities;d:\pycode\package1 ``` You can type such a command in a DOS console window, too, but the setting will then be active only for that one console window.
Changing your .bat file makes the change permanent and global to all programs. ###### Windows environment variable GUI On more recent versions of Windows, including XP and Vista, you can instead set ``` PYTHONPATH and other variables via the system environment variable GUI without having ``` **f** **|** ----- to ...
On XP, select the Control Panel, choose the System icon, pick the Advanced tab, and click the Environment Variables button to edit or add new variables (PYTHONPATH is usually a user variable).
Use the same variable name and values syntax shown in the DOS set command earlier.
The procedure is similar on Vista, but you may have to verify operations along the way. You do not need to reboot your machine, but be sure to restart Python if it’s open so that it picks up your changes—it configures its path at startup time only.
If you’re working in a Windows Command Prompt window, you’ll probably need to restart that to pick up your changes as well. ###### Windows registry If you are an experienced Windows user, you may also be able to configure the module search path by using the Windows Registry Editor.
Go to Start→Run... and type ``` regedit. Assuming the typical registry tool is on your machine, you can then navigate ``` to Python’s entries and make your changes.
This is a delicate and error-prone procedure, though, so unless you’re familiar with the registry, I suggest using other options (indeed, this is akin to performing brain surgery on your computer, so be careful!). ###### Path files Finally, if you choose to extend the module search path with a .pth file instead of th...
Python locates this file automatically when it starts up. Directory names in path files may be absolute, or relative to the directory containing the path file; multiple .pth files can be used (all their directories are added), and .pth files may appear in various automatically checked directories that are platform- an...
In general, a Python release numbered Python N.M typically looks for path files in _C:\PythonNM and_ _C:\PythonNM\Lib\site-packages on Windows, and_ in _/usr/local/lib/pythonN.M/site-packages and_ _/usr/local/lib/site-python on Unix and_ Linux.
See Chapter 21 for more on using path files to configure the sys.path import search path. Because environment settings are often optional, and because this isn’t a book on operating system shells, I’ll defer to other sources for further details.
Consult your system shell’s manpages or other documentation for more information, and if you have trouble figuring out what your settings should be, ask your system administrator or another local expert for help. **|** **f** ----- ###### Python Command-Line Options When you start Python from a system command line ...
a shell prompt), you can pass in a variety of option flags to control how Python runs.
Unlike system-wide environment variables, command-line options can be different each time you run a script. The complete form of a Python command-line invocation in 3.0 looks like this (2.6 is roughly the same, with a few option differences): ``` python [-bBdEhiOsSuvVWx?] [-c command | -m module-name | script | - ] [...
To illustrate, consider the following script file, main,py, which prints the command-line arguments list made available to the script as sys.argv: _# File main.py_ ``` import sys print(sys.argv) ``` In the following command line, both python and main.py can also be complete directory paths, and the three argument...
The first item in sys.argv is always the script file’s name, when it is known: `c:\Python30> python main.py a b –c` _# Most common: run a script file_ ``` ['main.py', 'a', 'b', '-c'] ``` Other code format specification options allow you to specify Python code to be run on the command line itself (-c), to accept cod...
Leave off the “.py” suffix here, since the filename is a module: `c:\Python30> python -m main a b –c` _# Locate/run module as script_ ``` ['c:\\Python30\\main.py', 'a', 'b', '-c'] ``` The –m option also supports running modules in packages with relative import syntax, as well as modules located in .zip archives.
This switch is commonly used to run the ``` pdb debugger and profile profiler modules from a command line for a script invocation ``` rather than interactively, though this usage mode seems to have changed somewhat in **f** **|** ----- 3.0 (profile appears to have been affected by the removal of execfile in 3.0, a...
These arguments are consumed by Python itself and are not meant for the script being run.
For example, -O runs Python in optimized mode, -u forces standard streams to be unbuffered, and –i enters interactive mode after running a script: `c:\Python30> python –u main.py a b -c` _# Unbuffered output streams_ Python 2.6 supports additional options that promote 3.0 compatibility (−3, `-Q) and` detecting incons...
See the Python manuals or reference texts for more details on available command-line options.
Or better yet, ask Python itself—run a command-line form like this: ``` c:\Python30> python -? ``` to request Python’s help display, which documents available command-line options. If you deal with complex command lines, be sure to also check out the standard library modules `getopt and` `optparse, which support mor...
The standard manual set is available in your Start button on Windows after Python is installed (option “Python Manuals”), and online at http://www.python.org. Look for the manual set’s top-level section titled “Using Python” for more platformspecific pointers and hints, as well as up-to-date cross-platform environment ...
Given Python’s widespread adoption, chances are good that answers to any usage questions you may have can be found with a web search. **|** ----- ----- ###### APPENDIX B ### Solutions to End-of-Part Exercises ###### Part I, Getting Started See “Test Your Knowledge: Part I Exercises” on page 70 in Chapter 3 for t...
Interaction.
Assuming Python is configured properly, the interaction should look something like the following (you can run this any way you like (in IDLE, from a shell prompt, and so on): ``` % python ...copyright information lines... >>> "Hello World!" 'Hello World!' >>> # Use Ctrl-D or Ctrl-Z to e...
Programs.
Your code (i.e., module) file module1.py and the operating system shell interactions should look like this: ``` print('Hello module world!') % python module1.py Hello module world! ``` Again, feel free to run this other ways—by clicking the file’s icon, by using IDLE’s Run→Run Module menu option, and so...
Modules.
The following interaction listing illustrates running a module file by importing it: ``` % python >>> import module1 Hello module world! >>> ``` Remember that you will need to reload the module to run it again without stopping and restarting the interpreter.
The question about moving the file to a different directory and importing it again is a trick question: if Python generates a _module1.pyc file in the original directory, it uses that when you import the module,_ even if the source code (.py) file has been moved to a directory not in Python’s ----- search path.
The .pyc file is written automatically if Python has access to the source file’s directory; it contains the compiled byte code version of a module. See Chapter 3 for more on modules. 4. Scripts.
Assuming your platform supports the #! trick, your solution will look like the following (although your `#!
line may need to list another path on your` machine): ``` #!/usr/local/bin/python (or #!/usr/bin/env python) print('Hello module world!') % chmod +x module1.py % module1.py Hello module world! ``` 5.
Errors. The following interaction (run in Python 3.0) demonstrates the sorts of error messages you’ll get when you complete this exercise.
Really, you’re triggering Python exceptions; the default exception-handling behavior terminates the running Python program and prints an error message and stack trace on the screen The stack trace shows where you were in a program when the exception occurred (if function calls are active when the error happens, the “Tr...