Previous Section Next Section

3.1 The python Program

The Python interpreter program is run as python (it's named python.exe on Windows). python includes both the interpreter itself and the Python compiler, which is implicitly invoked, as needed, on imported modules. Depending on your system, the program may have to be in a directory listed in your PATH environment variable. Alternatively, as with any other program, you can give a complete pathname to it at the command (shell) prompt, or in the shell script (or .BAT file, shortcut target, etc.) that runs it.[1] On Windows, you can also use Start Programs Python 2.2 Python (command line).

[1] This may involve using quotes, if the pathname contains spaces—again, this depends on your operating system.

3.1.1 Environment Variables

Besides PATH, other environment variables affect the python program. Some environment variables have the same effects as options passed to python on the command line; these are documented in the next section. A few provide settings not available via command-line options:

PYTHONHOME

The Python installation directory. A lib subdirectory, containing the standard Python library modules, should exist under this directory. On Unix-like systems, the standard library modules should be in subdirectory lib/python-2.2 for Python 2.2, lib/python-2.3 for Python 2.3, and so on.

PYTHONPATH

A list of directories, separated by colons on Unix-like systems and by semicolons on Windows. Modules are imported from these directories. This extends the initial value for Python's sys.path variable. Modules, importing, and the sys.path variable are covered in Chapter 7.

PYTHONSTARTUP

The name of a Python source file that is automatically executed each time an interactive interpreter session starts. No such file is run if this variable is not set, or if it is set to the path of a file that is not found. The PYTHONSTARTUP file is not used when you run a Python script: it is used only when you start an interactive session.

How you set and examine environment variables depends on your operating system: shell commands, persistent startup shell files (e.g., AUTOEXEC.BAT on Windows), or other approaches (e.g., Start Settings Control Panel System Environment on Windows/NT, 2000, and XP). Some Python versions for Windows also look for this information in the registry, in addition to the environment. On Macintosh systems, the Python interpreter is started through the PythonInterpreter icon and configured through the EditPythonPrefs icon. See http://www.python.org/doc/current/mac/mac.html for information about Python on the Mac.

3.1.2 Command-Line Syntax and Options

The Python interpreter command-line syntax can be summarized as follows:

[path]python {options} [ -c command | file | - ] {arguments}

Here, brackets ([ ]) denote something that is optional, braces ({ }) enclose items of which 0 or more may be present, and vertical bars (|) show a choice between alternatives (with none of them also being a possibility).

options are case-sensitive short strings, starting with a hyphen, that ask python for a non-default behavior. Unlike most Windows programs, python only accepts options starting with a hyphen, not with a slash. Python consistently uses slashes for file paths, as in Unix. The most useful options are listed in Table 3-1. Each option's description gives the environment variable (if any) that, when set to any value, requests the same behavior.

Table 3-1. Python frequently used command-line options

Option

Meaning (and equivalent environment variable)

-h

Prints a full list of options and summary help, then terminates

-i

Ensures an interactive session, no matter what (PYTHONINSPECT)

-O

Optimizes generated bytecode (PYTHONOPTIMIZE)

-OO

Like -O, but also removes documentation strings from the bytecode

-Q arg

Controls the behavior of division operator / on integers

-S

Omits the normally implicit import site on startup

-t

Warns about inconsistent usage of tabs and blank spaces

-tt

Like -tt, but raises an error rather than a warning

-u

Uses unbuffered binary files for standard output and standard error (PYTHONUNBUFFERED)

-U

Treats all literal strings as Unicode literals

-v

Verbosely traces import and cleanup actions (PYTHONVERBOSE)

-V

Prints the Python version number, then terminates

-W arg

Adds an entry to the warnings filter (covered in Chapter 17)

-x

Excludes (skips) the first line of the main script's source

-i is used to get an interactive session immediately after running some script, with variables still intact and available for inspection. You do not need it for normal interactive sessions. -t and -tt ensure that your tabs and spaces in Python sources are used consistently (see Chapter 4 for more information about whitespace usage in Python).

-O and -OO yield small savings of time and space in bytecode generated for modules you import: expect about 10% to 20% improvement in runtime, depending on your platform and coding style. However, with -OO, documentation strings will not be available. -Q determines the behavior of division operator / used between two integer operands (division is covered in Chapter 4). -W adds an entry to the warnings filter (warnings are covered in Chapter 17).

-u uses binary mode for standard output (and standard error). Some platforms, such as Windows, distinguish binary and text modes. Binary mode is needed when binary data is emitted to standard output, as in some Common Gateway Interface (CGI) scripts. -u also ensures that output is performed immediately, rather than buffered to enhance performance. This is necessary when delays due to buffering could cause problems, as in certain Unix pipelines.

After the options, if any, comes an indication of what Python program is to be run. A file path is that of a Python source or bytecode file to run, complete with file extension, if any. On any platform, you may use a slash (/) as the separator between components in this path. On Windows only, you may alternatively use a backslash (\). Instead of a file path, you can use -c command to execute a Python code string command. command normally contains spaces, so you need quotes around it to satisfy your operating system's shell or command-line processor. Some shells (e.g., bash) let you enter multiple lines as a single argument, so that command can be a series of Python statements. Other shells (e.g., Windows shells) limit you to a single line; command can then be one or more simple statements separated by semicolons (;), as discussed in Chapter 4. A hyphen, or the lack of any token in this position, tells the interpreter to read program source from standard input—normally, an interactive session. You need an explicit hyphen only if arguments follow. arguments are arbitrary strings: the Python application being run can access the strings as sys.argv.

For example, on a standard Windows installation of Python 2.2, you can enter the following at an MS-DOS Prompt (or Command Prompt):

C:\> python22\python -c "import time; print time.asctime(  )"

to have Python emit the current date and time. On an installation of Python from sources, on Cygwin, Linux, OpenBSD, or other Unix-like systems, you can enter the following at a shell prompt:

$ /usr/local/bin/python -v

to start an interactive session with verbose tracing of import and cleanup. In each case, you can start the command with just python (you do not have to specify the full path to the Python executable) if the directory of the Python executable is in your PATH environment variable.

3.1.3 Interactive Sessions

When you run python without a script argument, python enters an interactive session and prompts you to enter Python statements or expressions. Interactive sessions are useful to explore, to check things out, and to use Python as a very powerful, extensible interactive calculator.

When you enter a complete statement, Python executes it. When you enter a complete expression, Python evaluates it. If the expression has a result, Python outputs a string representing the result, and also assigns the result to the variable named _ (a single underscore) so that you can easily use that result in another expression. The prompt string is >>> when Python expects a statement or expression, and ... when a statement or expression has been started but not yet completed. For example, Python prompts you with ... when you have opened a parenthesis on a previous line and have not closed it yet.

An interactive session is terminated by end-of-file on standard input (Ctrl-Z on Windows, Ctrl-D on Unix-like systems). The statement raise SystemExit also ends the session, as does a call to sys.exit( ), either interactively or in code being run (SystemExit and Python exception handling are covered in Chapter 6).

Line-editing and history facilities depend in part on how Python was built: if the optional readline module was included, the features of the GNU readline library are available. Windows NT, 2000, and XP have a simple but usable history facility for interactive text-mode programs like python. Windows 95, 98, and ME don't. You can use other line-editing and history facilities by installing the Alternative ReadLine package for Windows (http://newcenturycomputers.net/projects/readline.html) or pyrepl for Unix (http://starship.python.net/crew/mwh/hacks/pyrepl.html).

    Previous Section Next Section