Thursday, January 17, 2008

Tab completion in Python 2 and 3

Voici messieur et mesdames! A startup script for Python 2 and 3 which will initialize the 'readline' module to give you auto completion in the REPL. Save this under .python (or whichever name takes your fancy) in your home directory and set the environment variable PYTHONSTARTUP to the path name of .python.

Yes, yes I know; this is lame. Every decent snake charmer knows how to do this. But it's for my benefit (so that I don't have to retype it every time) and I figure that it might save you 15 minutes.

With no further ado:


try:
import readline

except ImportError:
print("Module readline not available.")

else:
def init_readline():
import rlcompleter
import atexit
import user
import os.path as path

history_file = path.join(user.home, ".py_readline_history")

def save_history():
readline.write_history_file(history_file)

readline.parse_and_bind("tab: complete")
try:
readline.read_history_file(history_file)
except IOError:
pass

atexit.register(save_history)

init_readline()
del init_readline

This code is in the public domain.