众所周知,Ipython
是一个了不起的工具,当我阅读它的源代码时,我发现它在prompt_toolkit
中使用了completer
。
我有一个程序使用lib readline
和completer
代码,如下所示,我想将其更改为prompt_toolkit
。我该怎么办?
class Completer(object):
def complete(self, text, state):
buffer = readline.get_line_buffer()
line = readline.get_line_buffer().split()
COMMANDS = actions.keys()
# show all commands
if not line:
return [c + ' ' for c in COMMANDS][state]
# account for last argument ending in a space
if RE_SPACE.match(buffer):
line.append('')
# resolve command to the implementation function
cmd = line[0].strip()
if cmd in COMMANDS:
impl = getattr(actions[cmd], 'complete')
args = line[1:]
if args:
return (impl(args) + [None])[state]
return [cmd + ' '][state]
results = [c + ' ' for c in COMMANDS if c.startswith(cmd)] + [None]
return results[state]
com = Completer()
if(sys.platform == 'darwin'):
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
readline.set_completer_delims(' /\t\n;')
readline.set_completer(com.complete)
readline.set_history_length(10000)
答案 0 :(得分:0)
在我阅读源代码之后,我发现我唯一需要做的就是重写函数Completer
。
Completer
的函数readline
希望您返回带有[州]的列表。
Completer
的函数prompt_toolkit.completion
是一个生成函数,我们只需要从单词列表中yield
。在python3中,我们可以使用关键字yield from
。
代码应如下所示:
from prompt_toolkit.completion import Completer, Completion
class MyCustomCompleter(Completer):
def get_completions(self, document, complete_event):
buffer = document.text
line = document.text.split()
COMMANDS = actions.keys()
# show all commands
if not line:
for i in [c for c in COMMANDS]:
yield Completion(i, start_position=-1 * len(document.text), display=i)
# account for last argument ending in a space
else:
if RE_SPACE.match(buffer):
line.append('')
# resolve command to the implementation function
cmd = line[0].strip()
if cmd in COMMANDS:
try:
impl = getattr(actions[cmd], 'complete')
except:
yield Completion(cmd, start_position=-1 * len(document.text))
else:
args = line[1:]
if args:
ret = impl(args)
if not ret:
pass
else:
for i in ret:
ret = cmd + ' ' + ' '.join(args[:-1]) + ' ' + i
ret = ' '.join(ret.split())
yield Completion(ret, start_position=-1 * (len(document.text)), display=i.split()[-1])
else:
yield Completion(cmd + ' ', start_position=-1 * len(document.text))
else:
results = [c for c in COMMANDS if c.startswith(cmd)]
for i in results:
yield Completion(i, start_position=-1 * len(document.text), display=i)
content = prompt(completer=MyCustomCompleter())