问题描述
我正在尝试使用python中的readline创建一个交互式命令行程序.
I'm trying to create an interactive command line program using readline in python.
run.py文件包含以下代码:
The file run.py contains the following code:
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键被视为自动完成键,并且得到了建议.
The problem is when I try to run the file directly from the terminal (i.e. python run.py) the TAB key is not considered as auto-completion key, instead it is considered 4 spaces, so I got no suggestions when I press the TAB key twice; However, if I imported the file from a python console (i.e. import run.py) the TAB key is considered auto-completion key and I got suggestions as expected.
问题似乎出在那
readline.parse_and_bind('tab: complete')
所以我尝试将其放入此处的单独配置文件中,但是问题保持不变.
so I tried to put it in a seperate config file as mentioned here but the problem remained the same.
所以问题是为什么会这样?以及我该如何解决.
So the question is why is this happening? and how can I fix it.
推荐答案
最后找到了答案,问题是我使用的是Mac,所以不是
Finally found the answer, and the problem was that I am using Mac, so instead of
readline.parse_and_bind('tab: complete')
我必须使用
readline.parse_and_bind('bind ^I rl_complete')
现在直接使用 python run.py 运行代码,我得到了预期的建议.
Now running the code directly using python run.py, I get the suggestions as expected.
这篇关于TAB键在python自动完成中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!