Tab-Complete and a Persistent History in Python

November 17, 2006 at 9:15 pm | Posted in python | 4 Comments

Earlier today, in #django on freenode, the topic of tab-complete in the python shell happened to come up – at first, I thought it wasn’t possible in standard python, and only in other python interpreters.

Thankfully, a link was posted with info on the readline and rlcomplete modules – at first, I couldn’t get their example working to load on startup, so upon further investigation, not only did I get that quirk worked out, but I stumbled across another module that lets you hook on start/exit to save/load a history file, much like bash.

Anyway, without any further ado, here’s the short and sweet version to get this setup:

import atexit
import os

historyPath = os.path.expanduser("~/.pyhistory")

    import readline
except ImportError:
    print "Module readline not available."
    import rlcompleter
    readline.parse_and_bind("tab: complete")
    if os.path.exists(historyPath):

def save_history(historyPath=historyPath):
        import readline
    except ImportError:
        print "Module readline not available."


Drop that in a file such as .pythonrc in your home directory, then point python to that by adding the path to the PYTHONSTARTUP environment variable in .bashrc or .bash_profile


  1. Why not use ipython?

    I was using the method described above until I came across ipython which seems to tie all this functionality up into a very nice command repl.

  2. Mainly because I don’t control all the servers I use python on, so I can’t just go installing another interpreter šŸ™‚

  3. ipython isn’t another shell — it’s a wrapper script. All it does is:


    import IPython

    Also, ipython is quite honestly the best enhancement to the python shell you can make. šŸ™‚

  4. You may want to add a readline.set_history_length(1000) line before the readline.write_history_file(historyPath) to limit the history file to 1000 (or whatever other number you’d like) lines.

Sorry, the comment form is closed at this time.

Blog at
Entries and comments feeds.

<span>%d</span> bloggers like this: