Reputation: 542
I'm trying to create an interactive command line program using readline in python.
The file run.py contains the following code:
import readline
class SimpleCompleter(object):
def __init__(self, options):
self.options = sorted(options)
return
def complete(self, text, state):
response = None
if state == 0:
# This is the first time for this text, so build a match list.
if text:
self.matches = [s for s in self.options if s and s.startswith(text)]
else:
self.matches = self.options[:]
try:
response = self.matches[state]
except IndexError:
response = None
return response
def input_loop():
line = ''
while line != 'stop':
line = input('Prompt ("stop" to quit): ')
print(f'Dispatch {line}')
# Register our completer function
completer = SimpleCompleter(['start', 'stop', 'list', 'print'])
readline.set_completer(completer.complete)
# Use the tab key for completion
readline.parse_and_bind('tab: complete')
# Prompt the user for text
input_loop()
The problem is when I try to run the file directly from the terminal (i.e. python run.py) the TAB key is not considered as auto-completion key, instead it is considered 4 spaces, so I got no suggestions when I press the TAB key twice; However, if I imported the file from a python console (i.e. import run.py) the TAB key is considered auto-completion key and I got suggestions as expected.
It seems that the problem is in the line
readline.parse_and_bind('tab: complete')
so I tried to put it in a seperate config file as mentioned here but the problem remained the same.
So the question is why is this happening? and how can I fix it.
Upvotes: 1
Views: 2097
Reputation: 542
Finally found the answer, and the problem was that I am using Mac, so instead of
readline.parse_and_bind('tab: complete')
I have to use
readline.parse_and_bind('bind ^I rl_complete')
Now running the code directly using python run.py, I get the suggestions as expected.
Upvotes: 5