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:

try:
	import readline
except ImportError:
	print 'Module readline not available.'
else:
	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 ~/.pythonstartup.py and set the environment variable in my shell’s profile:

export PYTHONSTARTUP=~/.pythonstartup.py

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.

Advertisements
This entry was posted in python and tagged , . Bookmark the permalink.

One Response to Line Editing for the Python Interpreter

  1. Debsankha says:

    Thanks for this very helpful piece of info. I never imagined it could be that simple!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s