September 17, 2009

Python Tips and Tricks: Tab completion in Python Shell: How to enable Autocomplete in python shell

Autocompletion using readline libraries is really helpful while working in a shell environment. Python has a support for the readline library, hence it is possible to use readline for autocompletion in python shell.

The following steps need to be followed to enable autocompletion or tab completion in the python shell:

1. Create a file called .pyrc in your home directory (you can name is anything, however, I preferred to call this .pyrc). This can be done by executing the following command:

touch ~/.pyrc

2. Open this file using your favourite editor, such as emacs or vim and add the following lines in the ~/.pyrc file

import rlcompleter
import readline
readline.parse_and_bind("tab: complete")

3. Now to ensure that the above code is executed each time python starts, add the following lines to the ~/.bashrc file. This is assuming you are using the bash shell.

export PYTHONSTARTUP="[path to pyrc file]/.pyrc"

Once this is done, execute your .bashrc file by executing

#> source ~/.bashrc

Now you can test this. The output would be something similar to this

Python 2.5.2 (r252:60911, Sep 30 2008, 15:42:03)
[GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>> import os

>> os.

Display all 224 possibilities? (y or n)


Anonymous said...

Create tip, Thank You

Michael said...

This is great. Thank you so much!

Eli said...

Works great. Thanks Ashwin!

Unknown said...

This very nice it is work with terminal.But i have create loop are method "Indentation" not working.(for using tap press)

Unknown said...

Very gread Job. But Loop Tap "Indentation" is not working