Sub topic 10
Editing lines and using command history
This chapter assumes you can start the shell, type expressions, and write multi-line blocks at the >>> and ... prompts. It covers how to fix a typo without retyping a line, how to recall earlier input, and how history is saved between sessions. It also covers what to do when the shell has no editing features.
What provides the editing
The Python interpreter does not implement line editing itself. When it starts interactively, it asks a library to read each line. The library depends on your platform and Python version.
| Situation | Library | Notes |
|---|---|---|
| Linux and macOS, Python 3.12 and earlier | GNU Readline or libedit (through the `readline` module) | The behavior can differ slightly, especially on macOS builds that use libedit. |
| Any platform, Python 3.13 and later | The new built-in REPL (derived from PyPy's `pyrepl`) | It adds multi-line editing, colored output, and a paste mode. |
| Windows, Python 3.12 and earlier | The Windows console | It has basic history and editing, with no `readline` module. |
The keys in this chapter work in all of these unless noted. If a key does nothing, you are probably on a build without the library. Check this at the end of the chapter.
Basic line editing
You can edit the line you are typing before you press Enter. Entering the line runs it, wherever the cursor is.
| Key | Action |
|---|---|
| Left / Right arrow | Move the cursor one character |
| Home / End | Jump to the start or end of the line |
| Backspace / Delete | Remove the character before or under the cursor |
| Ctrl+A / Ctrl+E | Jump to the start or end of the line (Readline and pyrepl) |
| Ctrl+K | Delete from the cursor to the end of the line (Readline and pyrepl) |
| Ctrl+U | Delete from the cursor to the start of the line (Readline) |
| Ctrl+W | Delete the word before the cursor (Readline) |
| Ctrl+L | Clear the screen |
| Ctrl+C | Abandon the current line and return to a fresh `>>>` prompt |
A typical fix looks like this. You type a misspelled call and notice the error before pressing Enter.
>>> math.sqr(16)Press the Left arrow, or Ctrl+A, to move back, correct the name, and then press Enter. If you pressed Enter first, the traceback tells you what went wrong. Recall the line with the Up arrow and fix it, instead of retyping it.
>>> import math
>>> math.sqr(16)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'math' has no attribute 'sqr'
>>> math.sqrt(16)
4.0In the last step, you press Up, move the cursor, insert the t, and press Enter.
Recalling earlier input
The shell keeps a list of the lines you typed. Navigate it with these keys:
- Up arrow (or Ctrl+P) moves to the previous entry.
- Down arrow (or Ctrl+N) moves to the next entry.
- Ctrl+R starts a reverse incremental search. Type part of an earlier line and the shell shows the most recent match. Press Ctrl+R again to move to an older match, and Enter to accept it.
Recalled lines are editable. You can change a recalled line and run it, and the original stays in the list unchanged.
Recalled entries are individual lines. In Readline-based shells, a multi-line block such as a for loop is recalled one line at a time, so you step back through each line with the Up arrow and press Enter after each, including the final empty line. In the Python 3.13 REPL, a block is recalled as a single unit, and you can edit across its lines before running it.
>>> for i in range(3):
... print(i * i)
...
0
1
4After this, in a 3.13 REPL, pressing Up brings back the whole loop. In older shells, pressing Up brings back print(i * i), and you must press Up again for the for line.
Seeing and using history programmatically
On builds that have the readline module, you can inspect history from Python. The module's functions work on the same list the Up arrow uses.
import readline
count = readline.get_current_history_length()
for number in range(1, count + 1):
print(number, readline.get_history_item(number))Run in a script, this prints nothing useful, because a script has no interactive history. Type the same lines at the >>> prompt to see your session. History numbering starts at 1, so the loop starts there.
Be careful about relying on this. The readline module is missing on some platforms, notably Windows builds before 3.13, and import readline then raises ModuleNotFoundError. In code that might run there, guard the import:
try:
import readline
except ImportError:
readline = None
print("history available:", readline is not None)The tab key and completion
When readline is active, Tab completes names. It is not strictly history, but you use it in the same way, to avoid retyping.
>>> import math
>>> math.sq<Tab>If a single name matches, the shell finishes it as math.sqrt. If several names match, a second Tab press lists them. Completion works on names defined in the session, on module attributes after a dot, and on keywords.
There is one common trap. In a Readline-based shell, a Tab at the start of a line inserts a literal tab instead of completing. That is usually what you want inside a block, where you indent the body. If you need real indentation, use four spaces, because mixing tabs and spaces in a block can cause an IndentationError or TabError.
Saving history between sessions
Whether history survives after you exit depends on the platform.
- With the Python 3.13 REPL, history is saved automatically to a file in your home directory,
.python_history. You can change the location with thePYTHON_HISTORYenvironment variable. - With older Python on Linux and macOS, the default interactive startup code also saves history to
~/.python_historywhen the shell exits normally. A session that is killed, or a terminal that is closed abruptly, might not save its lines. - With Windows builds that have no
readline, history lasts only for the current session.
This file is plain text and records everything you type, including anything sensitive. Do not type passwords or API keys at the prompt. If you did, delete the line from ~/.python_history after leaving the shell.
You can control saving explicitly with a startup file. The PYTHONSTARTUP environment variable names a file that Python runs at the start of each interactive session. The next example sets up a history file in a way that works on older versions with readline.
# ~/.pythonstartup.py
import atexit
import os
try:
import readline
except ImportError:
readline = None
if readline is not None:
history_path = os.path.expanduser("~/.my_python_history")
try:
readline.read_history_file(history_path)
except FileNotFoundError:
pass
readline.set_history_length(1000)
atexit.register(readline.write_history_file, history_path)Point PYTHONSTARTUP at the file before you start Python:
export PYTHONSTARTUP=~/.pythonstartup.py
python3Three details matter here:
- The first run has no history file, so
read_history_fileraisesFileNotFoundError. Thetryblock handles this. set_history_length(1000)limits the file so it does not grow without bound.atexit.registerwrites the file when the interpreter exits normally. Python does not runatexithandlers when the process is killed by a signal it does not handle.
The startup file runs in the same namespace as your session, so names it defines, such as os and atexit, are visible at the prompt. Delete them there with del if they clutter dir().
Changing key bindings
Readline reads a configuration file, ~/.inputrc, that controls key bindings for every program that uses it, including Python. A common addition makes the Up and Down arrows search only for entries that start with what you have already typed:
"\e[A": history-search-backward
"\e[B": history-search-forwardWith this, typing import and pressing Up jumps to the most recent line that began with import. The Python 3.13 REPL does not read .inputrc, so these bindings only apply to the Readline-based shell. Terminals can send different escape sequences for arrow keys, so you might need to adjust the codes.
Pasting code
Pasting several lines into the shell is a frequent source of confusion. In a Readline-based shell, each pasted line is treated as if you had typed it. A blank line inside a pasted function ends the block early, and the next indented line then causes an error:
>>> def greet(name):
... message = "Hello, " + name
...
>>> return message
File "<stdin>", line 1
return message
IndentationError: unexpected indentRemove blank lines inside the pasted block, or paste the code into a file instead. The 3.13 REPL has a paste mode, entered with F3, that accepts a block exactly as pasted, including blank lines. Press F3 again to leave it.
Edge cases
- History with duplicates. Readline might store every repeated line. If you want to avoid this, a different Readline setting,
set history-ignore-dups, is not available in all versions. Use search (Ctrl+R) rather than repeated Up presses when history is long. - Lines starting with a space. Some shells skip these in history, but Python does not by default.
- Using
_and history together. The_variable holds the last result, but recalling a line re-evaluates it. Pressing Up and Enter on_ * 10runs it against the current value of_, so the output changes each time. - No editing at all. If the arrow keys print
^[[Aand similar sequences, the shell has no editing library. Install Python from a build that includesreadline, use a newer Python, or run the shell inside an environment that provides editing, such asrlwrap python3.
The last point is easy to test:
>>> 2 + 3
5
>>> _ * 10
50Press Up twice and Enter. You get 50 again from the first of those lines being recalled? Not exactly. The second Up lands on 2 + 3, so you get 5, and _ becomes 5. Recall is just retyping, so results depend on the current state.
Summary of decisions
- Fix a typo: press Up, edit the line, and press Enter.
- Find an old command: use Ctrl+R rather than many Up presses.
- Keep history between sessions: rely on the default file, or set up
PYTHONSTARTUPif your build has no default. - Paste a block: remove blank lines, use paste mode in 3.13, or put the code in a file.
- Keep secrets out of the shell, because the history file stores them in plain text.
Exercise
You paste a five-line function into an older Python shell on Linux. A blank line separates its second and third lines, and you then get an IndentationError. Why does it happen, and what are two ways to avoid it? Also, where would your history be saved after a normal exit, and what is one risk of that file?
Show answer
The older shell treats each pasted line as typed input, so the blank line ends the function block early, and the remaining indented lines are read as a new statement with an unexpected indent. Avoid it by removing blank lines in the pasted block, or by putting the function in a file and loading it with an import or python3 -i. In Python 3.13 you can also use paste mode (F3). After a normal exit, history is saved to ~/.python_history. The file is plain text, so anything sensitive you typed, such as a password, is stored there.
Exercise
You use the Up arrow to recall _ * 10 after two other calculations. Will the result match the first time you ran it? Explain.
Show answer
Not necessarily. Recall only puts the text back on the line. Running it evaluates the expression again, using whatever _ holds at that moment, which is the most recent echoed result. If other results were echoed in between, the output is different.