[英]TAB key not working in python auto-complete
我正在尝试使用 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')
所以我尝试将它放在一个单独的配置文件中,如此处所述,但问题仍然存在。
所以问题是为什么会发生这种情况? 以及我该如何解决。
终于找到答案了,问题是我用的是Mac,所以不是
readline.parse_and_bind('tab: complete')
我必须使用
readline.parse_and_bind('bind ^I rl_complete')
现在直接使用python run.py运行代码,我得到了预期的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.