Python tab completion

From Exterior Memory
Jump to: navigation, search

To enable tab completion in the interactive Python shell:

1. Install py-readline

e.g. for Python 3.7 using MacPorts, run:

sudo port install py37-gnureadline

You need the GNU readline utilities. For me, the libedit compiled version of readline didn't work. You can check if readline is compiled with GNU readline or libedit by examining the documentation header of the readline module.

>>> import readline
>>> readline.__doc__
Importing this module enables command line editing using GNU readline.

If it says libedit, tab completion may not work:

Importing this module enables command line editing using libedit readline.

2. Import completion function, and bind the tab key to it

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

3. Enable tab completion in your startup script

To enable tab completion for all sessions, create the following .pythonrc file:

# ~/.pythonrc
# enable syntax completion
try:
    import readline
except ImportError:
    print("Module readline not available.")
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")
    if "libedit" in readline.__doc__:
        print("Readline compiled with libedit instead of GNU readline. Tab completion may fail.")

and make sure the file is read for every python shell

export PYTHONSTARTUP=~/.pythonrc