Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you see the entire command history in interactive Python?

Tags:

python

macos

People also ask

How can I see all command line history?

Here's how: Open Start. Search for Command Prompt, and click the top result to open the console. Type the following command to view the command history and press Enter: doskey /history.

Where is Python history stored?

The History Log is stored in the . spyder-py3 (Python 3) or spyder (Python 2) directory in your user home folder (by default, C:/Users/username on Windows, /Users/username for macOS, and typically /home/username on GNU/Linux).

What is history function in Python?

The history() function above has an optional parameter to specify a maximum number of lines to be printed. If no argument is received, history() will print all commands given at the start of the session.


Code for printing the entire history:

Python 3

One-liner (quick copy and paste):

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

(Or longer version...)

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

Python 2

One-liner (quick copy and paste):

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

(Or longer version...)

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

Note: get_history_item() is indexed from 1 to n.


Use readline.get_current_history_length() to get the length, and readline.get_history_item() to view each.


With python 3 interpreter the history is written to
~/.python_history


If you want to write the history to a file:

import readline
readline.write_history_file('python_history.txt')

The help function gives:

Help on built-in function write_history_file in module readline:

write_history_file(...)
    write_history_file([filename]) -> None
    Save a readline history file.
    The default filename is ~/.history.

In IPython %history -g should give you the entire command history. The default configuration also saves your history into a file named .python_history in your user directory.


Since the above only works for python 2.x for python 3.x (specifically 3.5) is similar but with a slight modification:

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

note the extra ()

(using shell scripts to parse .python_history or using python to modify the above code is a matter of personal taste and situation imho)