Home > python > python – Adding tab completion to the interactive prompt

python – Adding tab completion to the interactive prompt

Problem:
You want tab completion in the interactive prompt *but* you do not want to use ipython (Why?).

Solution:
1. Create a file called .pythonstartup on your home directory. Then add the text below.

# python startup file
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab:complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOERROR:
    pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter

2. Add the following to your ~/.bash_profile file.

PYTHONSTARTUP=~/.pythonstartup
export PYTHONSTARTUP

3. Add to your ~/.bashrc

source ~/.bash_profile

4. Open a new terminal and check if PYTHONSTARTUP is enabled.

$ env | grep PYTHONSTARTUP
PYTHONSTARTUP=/home/<user>/.pythonstartup

5. Finally fire up python on the prompt.

$ python
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> csv.<tab>
csv.Dialect              csv.__doc__              csv.__subclasshook__(
csv.DictReader           csv.__file__             csv.__version__
csv.DictWriter           csv.__format__(          csv.excel
csv.Error(               csv.__getattribute__(    csv.excel_tab
csv.QUOTE_ALL            csv.__hash__(            csv.field_size_limit(
csv.QUOTE_MINIMAL        csv.__init__(            csv.get_dialect(
csv.QUOTE_NONE           csv.__name__             csv.list_dialects(
csv.QUOTE_NONNUMERIC     csv.__new__(             csv.re
csv.Sniffer              csv.__package__          csv.reader(
csv.StringIO(            csv.__reduce__(          csv.reduce(
csv._Dialect(            csv.__reduce_ex__(       csv.register_dialect(
csv.__all__              csv.__repr__(            csv.unregister_dialect(
csv.__class__(           csv.__setattr__(         csv.writer(
csv.__delattr__(         csv.__sizeof__(          
csv.__dict__             csv.__str__(             
>>> csv.

Source:
Expert Python Programming Book by Tarek Ziade

Advertisements
Categories: python
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: