Previous Page
Next Page

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 a command (shell) prompt, or in the shell script (or .BAT file, shortcut target, etc.) that runs it.[*] On Windows, you can also use Start Programs Python 2.4 Python (command line).

[*] This may involve using quotes if the pathname contains spacesagain, 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, as documented in the next section. A few environment variables 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.3 for Python 2.3, lib/python-2.4 for Python 2.4, 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 list 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 Classic View System Advanced Environment on Windows 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 can be started as in other Unix-like systems, but there are also other options, including a MacPython-specific IDE. For more information about Python on the Mac, see http://www.python.org/doc/current/mac/mac.html.

3.1.2. Command-Line Syntax and Options

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

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

Here, brackets ([]) enclose something that is optional, braces ({}) enclose items of which 0 or more may be present, and vertical bars (|) mean a choice among alternatives.

Options are case-sensitive short strings, starting with a hyphen, that ask python for a nondefault behavior. Unlike most Windows programs, python accepts only options that start with a hyphen (-), not with a slash. Python consistently uses a slash (/) 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)

-c

Specifies Python statements as part of the command line

-E

Ignores all environment variables

-h

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

-i

Ensures an interactive session, no matter what (PYTHONINSPECT)

-m

Specifies a Python module to run as the main script

-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 implicit import site on startup (covered in "The site and sitecustomize Modules" on page 338)

-t

Warns about inconsistent usage of tabs and blank spaces

-tt

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

-u

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

-v

Verbosely traces module import and cleanup actions (PYTHONVERBOSE)

-V

Prints the Python version number, then terminates

-W arg

Adds an entry to the warnings filter (covered in "Filters" on page 472)

-x

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


Use -i when you want to get an interactive session immediately after running some script, with variables still intact and available for inspection. You do not need -i for normal interactive sessions, although it does no harm. -t and -tt ensure that your tabs and spaces in Python sources are used consistently (see "Lines and Indentation" on page 33 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, and specifically turn assert statements into no-operations, as covered in "The assert Statement" on page 138. With -OO, documentation strings will not be available. -Q determines the behavior of division operator / used between two integer operands (division is covered in "Division" on page 52). -W adds an entry to the warnings filter (warnings are covered in "The warnings Module" on page 471).

-u uses binary mode for standard output (and standard error). Some platforms, mostly Windows, distinguish binary and text modes. Binary mode is needed to emit binary data 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 needed when delays due to buffering could cause problems, as in some Unix pipelines.

After the options, if any, comes an indication of which 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 "Statements" on page 37. In Python 2.4, another way to specify which Python program is to be run is to use -m module. This option tells Python to load and run a module named module from some directory that is part of Python's sys.path.

A hyphen, or the lack of any token in this position, tells the interpreter to read program source from standard inputnormally, 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 items of the list sys.argv.

For example, on a standard Windows installation of Python 2.4, you can enter the following at an MS-DOS Prompt (or Command Prompt) to have Python emit the current date and time:

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

On a default installation of Python from sources, performed on Cygwin, Linux, OpenBSD, or other Unix-like systems, you can enter the following at a shell prompt to start an interactive session with verbose tracing of import and cleanup:

$ /usr/local/bin/python -v

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, check things out, and use Python as a 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 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 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).

In addition to the built-in Python interactive environment, and those offered as part of richer development environments covered in the next section, you can freely download other alternative, powerful interactive environments. The most popular one is IPython, http://ipython.scipy.org/, which offers a wealth of features.


Previous Page
Next Page