16.Appendix¶
16.1.Interactive Mode¶
There are two variants of the interactiveREPL. The classicbasic interpreter is supported on all platforms with minimal linecontrol capabilities.
On Windows, or Unix-like systems withcurses
support,a new interactive shell is used by default.This one supports color, multiline editing, history browsing, andpaste mode. To disable color, seeControlling color fordetails. Function keys provide some additional functionality.F1 enters the interactive help browserpydoc
.F2 allows for browsing command-line history with neither output nor the>>> and… prompts.F3 enters “paste mode”, whichmakes pasting larger blocks of code easier. PressF3 to return tothe regular prompt.
When using the new interactive shell, exit the shell by typingexitorquit. Adding call parentheses after those commands is notrequired.
If the new interactive shell is not desired, it can be disabled viathePYTHON_BASIC_REPL
environment variable.
16.1.1.Error Handling¶
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 status; 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 (usuallyControl-C orDelete) 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 atry
statement.
16.1.2.Executable Python Scripts¶
On BSD’ish Unix systems, Python scripts can be made directly executable, likeshell scripts, by putting the line
#!/usr/bin/env python3
(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+xmyscript.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.
16.1.3.The Interactive Startup 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.profile
feature 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'):exec(open('.pythonrc.py').read())
.If you want to use the startup file in a script, you must do this explicitlyin the script:
importosfilename=os.environ.get('PYTHONSTARTUP')iffilenameandos.path.isfile(filename):withopen(filename)asfobj:startup_file=fobj.read()exec(startup_file)
16.1.4.The Customization Modules¶
Python provides two hooks to let you customize it:sitecustomize andusercustomize. To see how it works, you need first to find the locationof your user site-packages directory. Start Python and run this code:
>>>importsite>>>site.getusersitepackages()'/home/user/.local/lib/python3.x/site-packages'
Now you can create a file namedusercustomize.py
in that directory andput anything you want in it. It will affect every invocation of Python, unlessit is started with the-s
option to disable the automatic import.
sitecustomize works in the same way, but is typically created by anadministrator of the computer in the global site-packages directory, and isimported beforeusercustomize. See the documentation of thesite
module for more details.
Footnotes
[1]A problem with the GNU Readline package may prevent this.