Python Completion function for GNU readline


Unix readline module has tab completion mechanism. To get these features, we have to use rlcompleter module. It can be used in python’s interactive mode.

To use this module, we should import it using −

import rlcompleter

There is a class called Completer class −

Method Completer.complete(text, state)

This method is used to return the tab completion output. If there is a ‘.’ in the text, then it will try to get all related members of that command. When there is no dot ‘.’ it will just complete the text.

Example Code

import rlcompleter
import sys
my_completer = rlcompleter.Completer()
phrase_list = ['co', 'sys.m', 'cal']
for phrase in phrase_list:
   print(phrase + ' (TAB): ', end='')
   try:
      for i in range(50):
         terms = my_completer.complete(phrase, i)
         if terms is None:
            break
            print(terms, end='\t')
    except:
       pass
    print()

Output

$ python3 example.py
co (TAB): continue    compile(    complex(    copyright(    
sys.m (TAB): sys.maxsize    sys.maxunicode    sys.meta_path    sys.modules    
cal (TAB): callable(

Updated on: 30-Jul-2019

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements