简体   繁体   English

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

[英]TAB key not working in python auto-complete

I'm trying to create an interactive command line program using readline in python.我正在尝试使用 python 中的 readline 创建一个交互式命令行程序。

The file run.py contains the following code:文件 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()

The problem is when I try to run the file directly from the terminal (ie 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;问题是当我尝试直接从终端运行文件(即python run.py )时,TAB 键不被视为自动完成键,而是被视为 4 个空格,所以当我按下 TAB 时我没有得到任何建议键两次; However, if I imported the file from a python console (ie import run.py ) the TAB key is considered auto-completion key and I got suggestions as expected.但是,如果我从 python 控制台(即import run.py )导入文件,则 TAB 键被视为自动完成键,我得到了预期的建议。

It seems that the problem is in the line看来问题出在一线

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.以及我该如何解决。

Finally found the answer, and the problem was that I am using Mac, so instead of终于找到答案了,问题是我用的是Mac,所以不是

readline.parse_and_bind('tab: complete')

I have to use我必须使用

readline.parse_and_bind('bind ^I rl_complete')

Now running the code directly using python run.py , I get the suggestions as expected.现在直接使用python run.py运行代码,我得到了预期的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM