How can I get tab-completion in the interactive Python interpreter?

11,639

First, create a new file called .pythonstartup.py in your home directory. Put the following script in it:

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

The parentheses around the string ensure that it works with both Python 2 and Python 3.

Every time the interactive interpreter is started, it executes a script defined in $PYTHONSTARTUP, if there is one. To set it to execute the above script, type

export PYTHONSTARTUP="~/.pythonstartup.py"

You should write this line to your .bashrc or .bash_profile file, so that it's automatically executed when a new shell is started.

Share:
11,639

Related videos on Youtube

flo
Author by

flo

I'm a Software Developer in Berlin, Germany.

Updated on September 17, 2022

Comments

  • flo
    flo almost 2 years

    I often use Python 3000's interactive interpreter, but it's missing the convenience of tab-completion I'm used to from ipython, which isn't available for Python 3.x.

    How do I enable tab completion in all of them, 2.6 and 3.x?

  • Pithikos
    Pithikos over 9 years
    NOTICE: This won't work if you start the terminal and then change directory. If you want this method to work no matter the directory you are, you should use the full path like export PYTHONSTARTUP="/home/user/.pythonstartup.py"
  • Mikael Fremling
    Mikael Fremling over 8 years
    Your can make the export a bit more tolerant by having export PYTHONSTARTUP=~/.pythonstartup.py
  • chris
    chris about 7 years
    This doesn't work if you start a file in interactive mode, e.g. python -i main.py. Any way to do that?