最后,我在第 7 次重写后弄明白了。比我想要的有点混乱,但可行,可能我稍后会清理它。无论如何,这是代码:
"""defined earlier in the script:"""
COMMANDS=['show', 'exit', 'ship']
def complete(text, state, list = COMMANDS):
for option in list:
if option.startswith(text):
if not state:
return option
else:
state -= 1
def precomplete(text, state):
BUFFER=readline.get_line_buffer()
args=[None,None,None,None,None,None,None,None,None,None]
argtemp=[]
if BUFFER != "":
i=-1
while i != BUFFER.count(" "):
if BUFFER.count(" ") >= 0:
if BUFFER.count(" ") == 0: #1 because len() starts couting at 1
return complete(text, state)
else:
print "Else triggered"
o=0
verb=[]
while complete(BUFFER.split()[0],o):
verb.append(complete(BUFFER.split()[0],o))
o=o+1
if len(verb) == 1:
verb=verb[0]
print verb
if BUFFER.count(" ") >= 1:
if BUFFER.count(" ") == 1:
if verb == 'show':
return complete(text, state, ['mac', 'ip', 'arp'])
else:
o=0
while complete(BUFFER[1],o,['mac', 'ip', 'arp']):
argtemp.append(complete(BUFFER[1],o,['mac', 'ip', 'arp']))
o=o+1
if len(argtemp) == 1:
argtemp==argtemp[0]
i=i+1
else:
return complete(text,state)
readline.parse_and_bind("tab: complete")
readline.set_completer(precomplete)
编辑:完整代码:http://codepad.org/W3VHURUx