关于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++
本文作者:学不会xuebuhui
本文链接:https://www.cnblogs.com/codedingzhen/p/17816906.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步