How to Get the Command History in Python?

3.7/5 - (3 votes)

If you’re working with the command line in Windows or the terminal in Linux and macOS, you know about the feature of the command-line history. You can access all previously issued commands with the arrow up or arrow down keys.

As a Python coder, you want to be able to control everything from your Python shell. This naturally leads to the following question.

How to See the Command History in Python?

Problem Formulation: How to get the entire command history in Python—all commands that have been executed in the interactive Python session?

Method 1: Python 3 One-Liner with readline.get_history_item()

The readline module works in combination with Unix-like operating systems such as macOS and Linux. This one-liner is easy to copy and paste into your Python shell to access the command history in Python:

import readline; print('\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())]))

Method 2: Python 3 Multi-Liner with readline

This multi-liner does the same as the previous one-liner—it’s just more readable and less concise. πŸ˜‰

import readline
for i in range(readline.get_current_history_length()):
    print(readline.get_history_item(i + 1))

Method 3: Python 2 One-Liner with readline

Okay, some people may still use Python 2. In this case, you’ll need to slightly modify the previous one-liner to obtain:

import readline; print '\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())])

Method 4: Print File for Unix-Like OS

The following file contains the history: ~/.python_history. You can access it with the following command on macOS or Linux:

$ cat ~/.python_history

Note that you need to quit() the interpreter for the current session history to be included in the file ~/.python_history.

Method 5: Write History Into a File

The readline module also provides a function write_history_file() to write the command history into a file with name, say, '‘. Pass the desired filename into the function and Python will dump the Python commands into a new file with the given filename.

import readline

Method 6: Use Up and Down Arrows If You’re Running Python Shell From Command Line

If you’ve opened a Python session from the command line, you can use up and down arrows to get the previous commands because Python uses the same history mechanism as the operating system:

Programming Humor

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!