Line Editing for the Python Interpreter

The interactive python interpreter is a highly useful tool. When writing python code, I always run it in a terminal to test things and to access the documentation. Unfortunately, the built-in line editing capabilities are limited: There's no history, tab-completion, or other advanced editing features that shells like bash provide. Few people seem to know that it's simple to add all of that using a few lines of code.

Like bash, the python interpreter can use readline on Unix systems:

    import readline
except ImportError:
    print 'Module readline not available.'
    import rlcompleter
    readline.parse_and_bind('tab: complete')

This code from the rlcompleter module's documentation has to be executed at startup, so python's PYTHONSTARTUP mechanism comes to help. Save it to a file (it doesn't have to be executable) and let the PYTHONSTARTUP environment variable point to its location. On my system, I created a file ~/ and set the environment variable in my shell's profile:


To test this, start the python interpreter, and import the sys module. Then type sys. and hit the tab key. A list of attributes and functions available in the module should be displayed.

That's pretty cool already, but it's not all there is to it. See the readline module's documentation and the example there for what's possible.