我正在尝试使用python中的readline创建一个交互式命令行程序。
run.py文件包含以下代码:
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()
问题是,当我尝试直接从终端运行文件(即 python run.py )时,TAB键不被视为自动完成键,而是被视为4个空格,所以当我按两次TAB键时没有任何建议。但是,如果我从python控制台(即 import run.py )导入了文件,则TAB键被视为自动完成键,并且得到了建议。
问题似乎出在那
readline.parse_and_bind('tab: complete')
所以我试图将其放在here中提到的单独的配置文件中,但问题仍然相同。
所以问题是为什么会这样?以及我该如何解决。
答案 0 :(得分:1)
最后找到了答案,问题是我使用的是Mac,所以代替了
readline.parse_and_bind('tab: complete')
我必须使用
readline.parse_and_bind('bind ^I rl_complete')
现在使用 python run.py 直接运行代码,我得到了建议。