225

I'm working on the default python interpreter on Mac OS X, and I Cmd+K (cleared) my earlier commands. I can go through them one by one using the arrow keys. But is there an option like the --history option in bash shell, which shows you all the commands you've entered so far?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
Lavanya
  • 2,848
  • 3
  • 18
  • 13

10 Answers10

393

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.

Dennis Golomazov
  • 16,269
  • 5
  • 73
  • 81
  • 33
    One liner: `import readline; print '\n'.join([str(readline.get_history_item(i)) for i in range(readline.get_current_history_length())])` – Matt Jul 02 '14 at 01:25
  • 25
    This answer (and its non-example counterpart) exemplifies how important examples are to people. Thanks. – Tim S. Sep 23 '15 at 21:53
  • 9
    Cool! I've added an `history()` function with the above in my Python interpreter startup script (a script that's pointed to by env. var `$PYTHONSTARTUP`). From now on, I can simply type `history()` in any interpreter session ;-) – sxc731 Feb 19 '16 at 09:09
  • 3
    Everytime I forget, how this is done, I come here for the answer, thank you Dennis. – Felipe Valdes Feb 11 '18 at 02:31
  • 3
    I starred this who knows when and I'm back to snag this goodness one more time. – berto Aug 01 '19 at 00:07
  • 1
    0 is my readline.get_current_history_length() despite having many lines in my history as accessed by up-arrow. Nothing is displayed, consequently. IPython 7.8.0 – Geoffrey Anderson Dec 23 '19 at 15:02
  • One liner for python3: `import readline; print('\n'.join([str(readline.get_history_item(i)) for i in range(readline.get_current_history_length())]))` – lobi Mar 24 '20 at 23:19
78

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
76

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

  • 1
    I don't have this directory and I use Python 3.5.2 –  Sep 27 '16 at 19:29
  • 1
    This would be for Unix-like OSes. I was able to retrieve my history on macOS with `cat ~/.python_history` – Ryan H. Nov 08 '16 at 21:38
  • 2
    Thanks for this answer. I later found this covered in the docs here: https://docs.python.org/3/library/site.html#readline-configuration – Jason V. Mar 28 '17 at 19:51
  • 4
    Unfortunately, history doesn't seem to get updated when using virtual environments :-/ – ChrisFreeman Feb 04 '18 at 20:35
  • 9
    You need to `quit()` the interpreter for the current session history to be included in `~/.python_history` – plx Sep 12 '18 at 18:37
  • while in the console, do: `%!cat ~/.python_history` – sAguinaga Feb 23 '21 at 10:25
  • Remember all that any credentials you use within the python interpreter will be saved in this file. At least, the file has 600 permissions. – Hans Deragon Aug 07 '23 at 19:52
20

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.
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
  • will this persist across python sessions like ruby's pry history? – lacostenycoder Mar 09 '19 at 10:45
  • Maybe this answer was written before the readline function, but why not use readline.write_history_file ? @lacostenycoder You can use readline to both read and write a history file that persists. – Joe Holloway Aug 15 '19 at 04:22
  • Very simple ! Though, on macos, it replaces each space character by the 4 characters sequence `\040`, which I turned back to space with `sed -e 's/\\040/ /g'` (or any replace command from within emacs or vi). – duthen Oct 01 '22 at 17:31
15

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.

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Yossarian42
  • 1,950
  • 17
  • 14
  • 1
    For help run `%history?`. Nice tips there. – Xopi García Feb 19 '21 at 13:43
  • To save to a file run: `from datetime import datetime; file01="qtconsole_hist_"+datetime.today().strftime('%Y%m%d%H%M%S')+".py";` and `%history -f $file01` – Xopi García Feb 19 '21 at 13:44
  • A file enables to see by lines, and not cells: `%hist -l 10 -n` # prints last 10 cells **VS** `!tail -n 10 $file01` # prints last 10 lines – Xopi García Feb 19 '21 at 13:51
  • I wish this answer got more upvotes. Such an amazing feature! Especially that you can search by sessions. Thanks for sharing it. – viam0Zah Jul 19 '21 at 13:41
5

@Jason-V, it really help, thanks. then, i found this examples and composed to own snippet.

#!/usr/bin/env python3
import os, readline, atexit
python_history = os.path.join(os.environ['HOME'], '.python_history')
try:
  readline.read_history_file(python_history)
  readline.parse_and_bind("tab: complete")
  readline.set_history_length(5000)
  atexit.register(readline.write_history_file, python_history)
except IOError:
  pass
del os, python_history, readline, atexit 
dzNET
  • 930
  • 1
  • 9
  • 14
5

A simple function to get the history similar to unix/bash version.

Hope it helps some new folks.

def ipyhistory(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        flen = len(str(hlen)) if not lastn else len(str(lastn))
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(": ".join([str(r if not lastn else r + lastn - hlen ).rjust(flen), readline.get_history_item(r)]))
    else:
        flen = len(str(-hlen))
        for r in range(1, -lastn + 1):
            print(": ".join([str(r).rjust(flen), readline.get_history_item(r)]))

Snippet: Tested with Python3. Let me know if there are any glitches with python2. Samples:

Full History : ipyhistory()

Last 10 History: ipyhistory(10)

First 10 History: ipyhistory(-10)

Hope it helps fellas.

Josiah Yoder
  • 3,321
  • 4
  • 40
  • 58
Doogle
  • 1,236
  • 1
  • 17
  • 17
  • hi, thanks. I made your code snippet into a file xx.py. then after opening python, I did import xx. THen I tried ipyhistory() but it says, ">>> ipyhistory Traceback (most recent call last): File "", line 1, in NameError: name 'ipyhistory' is not defined". What's wrong? – Chan Kim Feb 22 '19 at 01:51
  • I've [revised this to not print line numbers](https://stackoverflow.com/a/62802740/1048186) since those usually get in the way for me, but I liked the line-limiting ability. (Even on Unix, I usually `cut -c 8` them out.) – Josiah Yoder Jul 08 '20 at 20:02
4

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)

Jeff Cliff
  • 91
  • 3
  • 3
    Win10 `C:\>python -m pip install readline` => `Collecting readline` \n `Downloading https://files.pythonhosted.org/packages/f4/01/2cf081af8d880b44939a5f1b446551a7f8d59eae414277fd0c303757ff1b/readline-6.2.4.1.tar.gz (2.3MB)` \n `|████████████████████████████████| 2.3MB 1.7MB/s` \n `ERROR: Complete output from command python setup.py egg_info:` \n `ERROR: error: this module is not meant to work on Windows` \n `----------------------------------------` \n `ERROR: Command "python setup.py egg_info" failed with error code 1 in C:\Users\dblack\AppData\Local\Temp\pip-install-s6m4zkdw\readline\` – bballdave025 Jun 26 '19 at 17:09
  • 2
    @bballdave025 Yes, you can't `pip install readline`, but [`readline` is installed by default on Windows.](https://stackoverflow.com/questions/62802667/print-python-history-from-interactive-prompt-on-windows) – Josiah Yoder Jul 08 '20 at 20:39
  • Well, that makes things easier. Thanks @JosiahYoder – bballdave025 Jul 09 '20 at 22:07
  • @bballdave025 I since learned that it isn't installed by default on windows, but if you follow the link, the instructions give details -- something like installing pyreadline or something. – Josiah Yoder Jul 13 '20 at 12:32
1

This should give you the commands printed out in separate lines:

import readline
map(lambda p:print(readline.get_history_item(p)),
    map(lambda p:p, range(readline.get_current_history_length()))
)
ChrisFreeman
  • 5,831
  • 4
  • 20
  • 32
Idea4life
  • 21
  • 3
1

Rehash of Doogle's answer that doesn't printline numbers, but does allow specifying the number of lines to print.

def history(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(readline.get_history_item(r))
    else:
        for r in range(1, -lastn + 1):
            print(readline.get_history_item(r))
Josiah Yoder
  • 3,321
  • 4
  • 40
  • 58