按特定顺序完成关键字的制表符
Tab completion of keywords in specific order
我在我的程序中使用以下代码完成制表符
import readline
import logging
import sys
LOG_FILENAME = '/tmp/completer.log'
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
)
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)]
logging.debug('Text: %s', text)
logging.debug('%s matches: %s', repr(text), self.matches)
else:
self.matches = self.options[:]
logging.debug('(empty input) matches: %s', self.matches)
# Return the state'th item from the match list,
# if we have that many.
try:
response = self.matches[state]
except IndexError:
response = None
logging.debug('complete(%s, %s) => %s',
repr(text), state, repr(response))
return response
def input_loop():
line = ''
while line != 'stop':
line = input('>')
print('Dispatch %s' % line)
# Register our completer function
readline.set_completer(SimpleCompleter(['CREATE', 'INPUT', 'USERNAME', 'VIEW']+ [account_names]).complete)
# Use the tab key for completion
readline.parse_and_bind('tab: complete')
# Prompt the user for text
input_loop()
但是代码接受任何顺序的关键字,我如何更改它以便按特定顺序处理关键字。例如,如果第一个关键字是 CREATE,则下一个选项卡完成不应找到任何匹配项并允许用户输入帐户名。同样,如果第一个关键字是 INPUT,那么它应该匹配 USERNAME 或 PASSWORD,然后是帐户名。可以用 readline 做到这一点吗?
readline.get_line_buffer() 获取整个缓冲文本,您可以根据需要从中创建匹配项。
我在我的程序中使用以下代码完成制表符
import readline
import logging
import sys
LOG_FILENAME = '/tmp/completer.log'
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
)
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)]
logging.debug('Text: %s', text)
logging.debug('%s matches: %s', repr(text), self.matches)
else:
self.matches = self.options[:]
logging.debug('(empty input) matches: %s', self.matches)
# Return the state'th item from the match list,
# if we have that many.
try:
response = self.matches[state]
except IndexError:
response = None
logging.debug('complete(%s, %s) => %s',
repr(text), state, repr(response))
return response
def input_loop():
line = ''
while line != 'stop':
line = input('>')
print('Dispatch %s' % line)
# Register our completer function
readline.set_completer(SimpleCompleter(['CREATE', 'INPUT', 'USERNAME', 'VIEW']+ [account_names]).complete)
# Use the tab key for completion
readline.parse_and_bind('tab: complete')
# Prompt the user for text
input_loop()
但是代码接受任何顺序的关键字,我如何更改它以便按特定顺序处理关键字。例如,如果第一个关键字是 CREATE,则下一个选项卡完成不应找到任何匹配项并允许用户输入帐户名。同样,如果第一个关键字是 INPUT,那么它应该匹配 USERNAME 或 PASSWORD,然后是帐户名。可以用 readline 做到这一点吗?
readline.get_line_buffer() 获取整个缓冲文本,您可以根据需要从中创建匹配项。