The Python interpreter is usually installed as/usr/local/bin/python onthose machines where it is available; putting/usr/local/bin in yourUnix shell’s search path makes it possible to start it by typing the command
pythonto the shell. Since the choice of the directory where the interpreter lives isan installation option, other places are possible; check with your local Pythonguru or system administrator. (E.g.,/usr/local/python is a popularalternative location.)
On Windows machines, the Python installation is usually placed inC:\Python26, though you can change this when you’re running theinstaller. To add this directory to your path, you can type the followingcommand into the command prompt in a DOS box:
set path=%path%;C:\python26
Typing an end-of-file character (Control-D on Unix,Control-Z onWindows) at the primary prompt causes the interpreter to exit with a zero exitstatus. If that doesn’t work, you can exit the interpreter by typing thefollowing commands:importsys;sys.exit().
The interpreter’s line-editing features usually aren’t very sophisticated. OnUnix, whoever installed the interpreter may have enabled support for the GNUreadline library, which adds more elaborate interactive editing and historyfeatures. Perhaps the quickest check to see whether command line editing issupported is typing Control-P to the first Python prompt you get. If it beeps,you have command line editing; see AppendixInteractive Input Editing and History Substitution for anintroduction to the keys. If nothing appears to happen, or if^P is echoed,command line editing isn’t available; you’ll only be able to use backspace toremove characters from the current line.
The interpreter operates somewhat like the Unix shell: when called with standardinput connected to a tty device, it reads and executes commands interactively;when called with a file name argument or with a file as standard input, it readsand executes ascript from that file.
A second way of starting the interpreter ispython-ccommand[arg]...,which executes the statement(s) incommand, analogous to the shell’s-c option. Since Python statements often contain spaces or othercharacters that are special to the shell, it is usually advised to quotecommand in its entirety with single quotes.
Some Python modules are also useful as scripts. These can be invoked usingpython-mmodule[arg]..., which executes the source file formodule asif you had spelled out its full name on the command line.
Note that there is a difference betweenpythonfile andpython<file.In the latter case, input requests from the program, such as calls toinput() andraw_input(), are satisfied fromfile. Since this filehas already been read until the end by the parser before the program startsexecuting, the program will encounter end-of-file immediately. In the formercase (which is usually what you want) they are satisfied from whatever file ordevice is connected to standard input of the Python interpreter.
When a script file is used, it is sometimes useful to be able to run the scriptand enter interactive mode afterwards. This can be done by passing-ibefore the script. (This does not work if the script is read from standardinput, for the same reason as explained in the previous paragraph.)
When known to the interpreter, the script name and additional argumentsthereafter are passed to the script in the variablesys.argv, which is alist of strings. Its length is at least one; when no script and no argumentsare given,sys.argv[0] is an empty string. When the script name is given as'-' (meaning standard input),sys.argv[0] is set to'-'. When-ccommand is used,sys.argv[0] is set to'-c'. When-mmodule is used,sys.argv[0] is set to the full name of thelocated module. Options found after-ccommand or-mmodule are not consumed by the Python interpreter’s option processing butleft insys.argv for the command or module to handle.
When commands are read from a tty, the interpreter is said to be ininteractivemode. In this mode it prompts for the next command with theprimary prompt,usually three greater-than signs (>>>); for continuation lines it promptswith thesecondary prompt, by default three dots (...). The interpreterprints a welcome message stating its version number and a copyright noticebefore printing the first prompt:
pythonPython 2.6 (#1, Feb 28 2007, 00:02:06)Type "help", "copyright", "credits" or "license" for more information.>>>
Continuation lines are needed when entering a multi-line construct. As anexample, take a look at thisif statement:
>>>the_world_is_flat=1>>>ifthe_world_is_flat:...print"Be careful not to fall off!"...Be careful not to fall off!
When an error occurs, the interpreter prints an error message and a stack trace.In interactive mode, it then returns to the primary prompt; when input came froma file, it exits with a nonzero exit status after printing the stack trace.(Exceptions handled by anexcept clause in atry statementare not errors in this context.) Some errors are unconditionally fatal andcause an exit with a nonzero exit; this applies to internal inconsistencies andsome cases of running out of memory. All error messages are written to thestandard error stream; normal output from executed commands is written tostandard output.
Typing the interrupt character (usually Control-C or DEL) to the primary orsecondary prompt cancels the input and returns to the primary prompt.[1]Typing an interrupt while a command is executing raises theKeyboardInterrupt exception, which may be handled by atrystatement.
On BSD’ish Unix systems, Python scripts can be made directly executable, likeshell scripts, by putting the line
#! /usr/bin/env python(assuming that the interpreter is on the user’sPATH) at the beginningof the script and giving the file an executable mode. The#! must be thefirst two characters of the file. On some platforms, this first line must endwith a Unix-style line ending ('\n'), not a Windows ('\r\n') lineending. Note that the hash, or pound, character,'#', is used to start acomment in Python.
The script can be given an executable mode, or permission, using thechmod command:
$ chmod +x myscript.py
On Windows systems, there is no notion of an “executable mode”. The Pythoninstaller automatically associates.py files withpython.exe so thata double-click on a Python file will run it as a script. The extension canalso be.pyw, in that case, the console window that normally appears issuppressed.
It is possible to use encodings different than ASCII in Python source files. Thebest way to do it is to put one more special comment line right after the#!line to define the source file encoding:
# -*- coding: encoding -*-
With that declaration, all characters in the source file will be treated ashaving the encodingencoding, and it will be possible to directly writeUnicode string literals in the selected encoding. The list of possibleencodings can be found in the Python Library Reference, in the section oncodecs.
For example, to write Unicode literals including the Euro currency symbol, theISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value164. This script will print the value 8364 (the Unicode codepoint correspondingto the Euro symbol) and then exit:
# -*- coding: iso-8859-15 -*-currency=u"€"printord(currency)
If your editor supports saving files asUTF-8 with a UTF-8byte order mark(aka BOM), you can use that instead of an encoding declaration. IDLE supportsthis capability ifOptions/General/DefaultSourceEncoding/UTF-8 is set.Notice that this signature is not understood in older Python releases (2.2 andearlier), and also not understood by the operating system for script files with#! lines (only used on Unix systems).
By using UTF-8 (either through the signature or an encoding declaration),characters of most languages in the world can be used simultaneously in stringliterals and comments. Using non-ASCII characters in identifiers is notsupported. To display all these characters properly, your editor must recognizethat the file is UTF-8, and it must use a font that supports all the charactersin the file.
When you use Python interactively, it is frequently handy to have some standardcommands executed every time the interpreter is started. You can do this bysetting an environment variable namedPYTHONSTARTUP to the name of afile containing your start-up commands. This is similar to the.profilefeature of the Unix shells.
This file is only read in interactive sessions, not when Python reads commandsfrom a script, and not when/dev/tty is given as the explicit source ofcommands (which otherwise behaves like an interactive session). It is executedin the same namespace where interactive commands are executed, so that objectsthat it defines or imports can be used without qualification in the interactivesession. You can also change the promptssys.ps1 andsys.ps2 in thisfile.
If you want to read an additional start-up file from the current directory, youcan program this in the global start-up file using code likeifos.path.isfile('.pythonrc.py'):execfile('.pythonrc.py'). If you want to usethe startup file in a script, you must do this explicitly in the script:
importosfilename=os.environ.get('PYTHONSTARTUP')iffilenameandos.path.isfile(filename):execfile(filename)
Footnotes
| [1] | A problem with the GNU Readline package may prevent this. |
An Informal Introduction to Python