简体   繁体   English

Python命令行界面中的选项卡完成 - 如何捕获Tab事件

[英]Tab Completion in Python Command Line Interface - how to catch Tab events

I'm writing a little CLI in Python (as an extension to Mercurial) and would like to support tab-completion. 我在Python中编写了一个CLI(作为Mercurial的扩展),并且希望支持制表完成。 Specifically, I would like catch tabs in the prompt and show a list of matching options (just like bash). 具体来说,我想在提示中捕获标签并显示匹配选项列表(就像bash一样)。

Example: Enter section name: 示例:输入部分名称:

 ext*TAB*  
 extensions  
 extras

The problem is I'm not sure how to catch the Tab events. 问题是我不知道如何捕捉Tab事件。 I'm using the ui.prompt() API of Mercurial, which is just calling raw_input() under the hood. 我正在使用Mercurial的ui.prompt() API,它只是在ui.prompt()调用raw_input()

As far as I know, raw_input() only returns on 'enter' and if a user enters a tab, the string returned simply includes a "\\t" . 据我所知, raw_input()只返回'enter',如果用户输入一个tab,返回的字符串只包含一个"\\t"

For that you use the readline module. 为此,您使用readline模块。

Simplest code I can think: 我能想到的最简单的代码:

import readline
COMMANDS = ['extra', 'extension', 'stuff', 'errors',
            'email', 'foobar', 'foo']

def complete(text, state):
    for cmd in COMMANDS:
        if cmd.startswith(text):
            if not state:
                return cmd
            else:
                state -= 1

readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
raw_input('Enter section name: ')

Example usage: 用法示例:

Enter section name: <tab>
email      errors     extension  extra      foo        foobar    stuff
Enter section name: e<tab>
email      errors     extension  extra      
Enter section name: ext<tab>
extension  extra      

Besides completion, readline provides you with: 除了完成, readline为您提供:

  • Line editing 线路编辑
  • Keybinding configuration (emacs and vi modes included) 键绑定配置(包括emacs和vi模式)
  • History (up arrow to recall previous values) 历史(向上箭头以回忆以前的值)
  • History searching, saving and loading 历史搜索,保存和加载

标准库中作为rlcompleter模块提供了如何与readline一起完成制表完成的一个很好的例子 - 您不能按原样使用它(它基于当前在Python的main和builtin中定义的名称完成),但它显示了如何执行一般任务以及如何将其连接到readline

You should almost certainly be using the cmd module , which already implements tab completion and so on, and probably other parts of what you're trying to do, using the readline module and so on. 你几乎肯定会使用cmd模块 ,它已经实现了标签完成等等,可能还有你正在尝试做的其他部分,使用readline模块等等。 There's no point reinventing the wheel. 没有必要重新发明轮子。

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

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