TAB 键在 python 自动完成中不起作用

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')

所以我尝试将它放在单独的配置文件中,如前所述here,但问题仍然存在。

所以问题是为什么会这样?我该如何修复它。

终于找到答案了,问题是我用的是Mac,所以不是

readline.parse_and_bind('tab: complete')

我必须使用

readline.parse_and_bind('bind ^I rl_complete')

现在 运行 代码直接使用 python run.py,我得到了预期的建议。