Pimp my Interactive Interpreter

A couple of things that bother me about Python’s interactive interpreter:

  • Having to import commonly used modules like sys.
  • Not having history stored across interpreter sessions.
  • No tab-completion.

Of course, things like iPython and bpython help, but I generally prefer just a plain old python interactive interpreter session. Plus, the above three problems are easy to solve without installing any extra packages, but the way to solve them is documented in somewhat obscure locations. The solution?

First, create a file somewhere with the following text (I save mine to ~/.pystartup):

import atexit
import os
import readline
import rlcompleter
import sys
histfile = os.path.join(os.environ["HOME"], ".pyhist")
try:
    readline.read_history_file(histfile)
except IOError:
    pass
readline.parse_and_bind('tab: complete')

atexit.register(readline.write_history_file, histfile)
del os, histfile

Then, you just need to add a line to your .bashrc, .zshrc, or whatever else your shell uses:

export PYTHONSTARTUP=~/.pystartup

…and viola! Your interactive interpreter has just been pimped.

If you’re on Windows, I’m afraid I have bad news. This probably won’t work for you without using cygwin (as you will need readline).