Featureintro
Interactive mode
Also called Python REPL, Python shell, interactive interpreter.
In interactive mode the interpreter reads one statement at a time from a terminal, runs it, and prints the value of each expression. It is the Python REPL.
- Language
- Python
Synopsis
$ python3 start the REPL (the version banner, then the >>> prompt)
$ python3 -q start it with no banner
$ python3 -i script.py run the script, then stay in the REPL with its globals
>>> statement the primary prompt, sys.ps1, default '>>> '
... continuation the secondary prompt, sys.ps2, default '... '
>>> _ the value of the last expression that was shown
The interpreter is in interactive mode when it reads its commands from a terminal (a tty).1 To leave it, type the end-of-file character (Control-D on Unix, Control-Z then Enter on Windows) or call quit().2
Semantics
r1. When the interpreter reads commands from a tty, it is in interactive mode. It prints a banner with the version number and a copyright notice, then the primary prompt >>> . It shows the secondary prompt ... on the continuation lines of a compound statement, such as the body of an if or a for.1 Example: repl-prompts.
r2. After each statement that is an expression, the interpreter calls sys.displayhook with the value. The default hook does nothing for None. For any other value it prints repr(value) and saves the value in builtins._.3 So the REPL echoes 2 + 3 as 5, and it does not echo a call that returns None, such as print(). Example: repl-echo.
r3. In interactive mode, the interpreter assigns the last printed expression to the variable _. The tutorial uses it to "continue calculations" as with a desk calculator.4 The name _ lives in the builtins module, so a global variable named _ hides it (rule r2). Example: repl-underscore.
r4. sys.ps1 and sys.ps2 hold the two prompts. "These are only defined if the interpreter is in interactive mode."5 A statement typed at the prompt can test hasattr(sys, "ps1"). The attribute does not exist yet while the script of python -i script.py runs, because the interactive loop sets it when it starts; sys.flags.interactive tells if -i was given.6 When a prompt is not a string, the interpreter calls str() on it before each new command, so an object can make a dynamic prompt.5 Example: repl-detect.
r5. When a statement raises an exception that is not handled, the interpreter prints the traceback and returns to the primary prompt. The session goes on. When the input came from a file, the interpreter exits with a nonzero status instead.7 Example: repl-error.
r6. The interrupt character (usually Control-C) at a prompt cancels the input line and returns to the primary prompt. While a command runs, it raises KeyboardInterrupt.7
r7. The option -i enters interactive mode after the script, the -c command or the -m module has run, and it does so even when standard input is not a terminal. The option -q hides the banner.8
r8. If the environment variable PYTHONSTARTUP names a readable file, the interpreter runs that file before the first prompt, in the namespace of the session. It runs only for an interactive start, not for -i.9 8
r9. quit and exit are objects that the site module adds. Calling either one raises SystemExit. When printed, they show a message like "Use quit() or Ctrl-D (i.e. EOF) to exit".10 help() starts the interactive help system.
Examples
The examples below start a child interpreter with -i -q and feed it lines through a pipe, so the run is the same each time. A person at a terminal sees the same results, with the prompts in between.
The REPL echoes the value of each expression, and _ holds the last one (rules r2 and r3).
import subprocess
import sys
session = """\
2 + 3
x = 10
x * 4
_ + 1
None
print('hi')
"""
result = subprocess.run(
[sys.executable, "-i", "-q"], input=session, capture_output=True, text=True
)
print(result.stdout, end="")
5
40
41
hi
The assignment x = 10 shows nothing, because it is not an expression. None shows nothing (rule r2), and print('hi') shows its own output but not its return value, which is None.
The prompts go to standard error. A compound statement gets the secondary prompt until an empty line ends it (rule r1).
import subprocess
import sys
session = "for i in range(2):\n print(i)\n\n"
result = subprocess.run(
[sys.executable, "-i", "-q"], input=session, capture_output=True, text=True
)
print("stdout:", repr(result.stdout))
print("stderr:", repr(result.stderr))
stdout: '0\n1\n'
stderr: '>>> ... ... >>> \n'
An error does not end the session (rule r5).
import subprocess
import sys
session = "1 / 0\nprint('still here')\n"
result = subprocess.run(
[sys.executable, "-i", "-q"], input=session, capture_output=True, text=True
)
print(result.stdout, end="")
print(result.stderr.splitlines()[-2])
still here
ZeroDivisionError: division by zero
A program can tell if it runs in interactive mode, because sys.ps1 exists only there (rule r4).
import subprocess
import sys
check = "import sys; print(hasattr(sys, 'ps1'), sys.flags.interactive)"
def run(args, stdin=""):
result = subprocess.run([sys.executable, *args], input=stdin, capture_output=True, text=True)
return result.stdout.strip()
print("python -c: ", run(["-c", check]))
print("python -i -c: ", run(["-i", "-q", "-c", check]))
print("at the prompt: ", run(["-i", "-q"], stdin=check + "\n"))
python -c: False 0
python -i -c: False 1
at the prompt: True 1
With -i, the command runs before the interactive loop starts, so sys.ps1 is not set yet, but sys.flags.interactive is already 1.
Versions
Since 3.13
CPython has a second REPL, written in Python and based on code from PyPy. It starts by default when the REPL runs in a terminal. It adds multiline editing, colour,
help,exitandquitwithout parentheses, help browsing with F1, history browsing with F2 and a paste mode with F3.11 12
The environment variable PYTHON_BASIC_REPL turns the new REPL off and starts the parser-based one.13 With input from a pipe, as in the examples above, the session is not at a terminal, and the examples ran on CPython 3.12.
Tab completion and a history file (.python_history in the home directory) are on by default on systems with GNU Readline.14
Pitfalls
A script does not echo its expressions
The echo of rule r2 happens only in interactive mode. In a script, an expression statement computes its value and drops it. Code copied from a REPL session must call print().
This code runs but gives a wrong answer on purpose.
total = 2 + 3
total
print("done")
done
Assigning to _ stops the update
_ is a name in builtins. After _ = 'mine', the global _ hides the built-in one, and the REPL updates only the hidden one (rule r3).
This code runs but gives a wrong answer on purpose.
import subprocess
import sys
session = "_ = 'mine'\n1 + 1\n_\n"
result = subprocess.run(
[sys.executable, "-i", "-q"], input=session, capture_output=True, text=True
)
print(result.stdout, end="")
2
'mine'
del _ removes the global name, and the REPL's _ shows again.
Piped input without -i is a script
Without -i, input from a pipe is read as a script, not as a session (rule r1). Nothing is echoed.
This code runs but gives a wrong answer on purpose.
import subprocess
import sys
result = subprocess.run([sys.executable, "-q"], input="2 + 3\n", capture_output=True, text=True)
print(repr(result.stdout))
''
The basic REPL needs exit() with parentheses
In the parser-based REPL, a bare exit is an expression. The REPL prints the object, which shows a hint and does not exit (rule r9). The REPL of 3.13 and later accepts the bare word.12
Comparison
The tutorial names two enhanced interactive interpreters for Python: IPython, with "tab completion, object exploration and advanced history management", and bpython.14 The REPLs of other languages are on the page of each language.
Implementation notes
CPython has two REPLs. The default one of 3.13 and later is written in Python and uses code from the PyPy project. The other one is the traditional parser-based REPL, and PYTHON_BASIC_REPL selects it.11 13
References
- The Python Tutorial, Python 3.15, 2.1.2 Interactive Mode
- The Python Tutorial, Python 3.15, 2.1 Invoking the Interpreter
- sys, Python 3.15 documentation, sys.displayhook
- The Python Tutorial, Python 3.15, 3.1.1 Numbers
- sys, Python 3.15 documentation, sys.ps1, sys.ps2
- sys, Python 3.15 documentation, sys.flags, flags.interactive
- The Python Tutorial, Python 3.15, 16.1.1 Error Handling
- Python Setup and Usage, Python 3.15, 1.1.3 Miscellaneous options, -i and -q
- Python Setup and Usage, Python 3.15, 1.2 Environment variables, PYTHONSTARTUP
- Built-in Constants, Python 3.15 documentation, Constants added by the site module
- What's New In Python 3.13, A better interactive interpreter
- The Python Tutorial, Python 3.15, 16.1 Interactive Mode
- Python Setup and Usage, Python 3.15, 1.2 Environment variables, PYTHON_BASIC_REPL
- The Python Tutorial, Python 3.15, 14.1 Tab Completion and History Editing; 14.2 Alternatives to the Interactive Interpreter
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 4T47BQ Edit this page History Report an error Markdown