Printing command history within the python interactive terminal / REPL — simplified
Interactive terminal modes and REPLs (Read-Evaluate-Print-Loop) are the best way to quickly test a concept in your language of interest. For example, to practice python, swift, or node.js code in interactive mode, simply enter ‘python,’ ‘swift,’ or ‘node’:
After a few minutes in the terminal, you’ll realize that it can be frustrating to look through old commands, especially when you have to repeat a snippet of code due to a simple error. Fortunately, we can take advantage of the readline
module to write a simple history()
function, readily available for use inside any python REPL.
Customizing .pythonrc
In the terminal, enter vim ~/.pythonrc
to start writing into an rc file that will be executed at the start of every python REPL.
- If you already have a .pythonrc file, append the following code.
- If you don’t already have a .pythonrc file, writing the file in vim will save it to the desired location.
import readlinedef history(numLines=-1):
total = readline.get_current_history_length()
if numLines == -1:
# default value prints everything
numLines = total
if numLines > 0:
# range from n->end in order to…