关于tab 自动补全的实现方法(各平台都有)

基于python readline

  • 只有linux能用,windows没有
    实例解析:
import readline

# 自定义自动补全函数
def complete(text, state):
    commands = ["start", "stop", "restart", "status"]  # 定义一组可能的命令
    options = [i for i in commands if i.startswith(text)]  # 根据用户输入的text进行匹配
    if state < len(options):
        return options[state]
    else:
        return None

# 启用自动补全功能
readline.parse_and_bind("tab: complete")

# 设置自动补全函数
readline.set_completer(complete)
while True:
    # 从命令行获取用户输入
    user_input = input("Enter a command: ")  #拿到输入的命令,可以用来执行后续操作

以上是一个简单的通过readline 和startswith补全的代码,如果要实现多层的补全,进阶代码如下:

import readline

# 第一层补全的选项
first_level_options = ['apple', 'banana', 'cherry']

# 第二层补全的选项
second_level_options = {
    'apple': ['red', 'green', 'yellow'],
    'banana': ['small', 'medium', 'large'],
    'cherry': ['sweet', 'sour', 'tart']
}

# 定义补全的逻辑
def completer(text, state):
    if state == 0:  # 如果是第一次调用
        if text:  # 如果有输入文本
            matches = [option for option in first_level_options if option.startswith(text)]
        else:  # 如果没有输入文本
            matches = first_level_options
        readline.set_completer_delims(' ')  # 设置分隔符
        readline.set_completer(completer)  # 设置第一层补全的逻辑
    else:  # 如果已经进行了第一层补全
        first_level_completion = readline.get_line_buffer().split(' ')[0]  # 获取第一层补全的结果
        matches = [option for option in second_level_options.get(first_level_completion, []) if option.startswith(text)]

    try:
        return matches[state]
    except IndexError:
        return None

# 设置补全的逻辑
readline.set_completer(completer)

# 开启补全
readline.parse_and_bind('tab: complete')

基于GNU_readline

  • 特定是跨平台,基于c/c++
posted @ 2023-11-08 11:06  学不会xuebuhui  阅读(91)  评论(0编辑  收藏  举报
Language: javascript