但不仅仅是在字符串的开头

但不仅仅是在字符串的开头

本文介绍了如何做 python 命令行自动补全,但不仅仅是在字符串的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python,通过它的 readline 绑定允许很好的命令行自动完成(如 此处).

Python, through it's readline bindings allows for great command-line autocompletion (as described in here).

但是,完成似乎只在字符串的开头起作用.如果您想匹配字符串的中间或结尾,则 readline 不起作用.

But, the completion only seems to work at the beginning of strings. If you want to match the middle or end of a string readline doesn't work.

我想在命令行 python 程序中自动完成字符串,方法是将我键入的内容与可用字符串列表中的任何字符串进行匹配.

I would like to autocomplete strings, in a command-line python program by matching what I type with any of the strings in a list of available strings.

  • 我想要的自动完成类型的一个很好的例子是当您在收件人"字段中输入时在 GMail 中发生的类型.如果您键入某个联系人的姓氏,其显示效果与您键入她的名字的效果一样.
  • 可能需要使用向上和向下箭头或其他一些方法来从匹配的字符串中进行选择(在 readline 的情况下不需要),这对我来说很好.
  • 我的特定用例是发送电子邮件的命令行程序.
  • 具体的代码示例会很有帮助.

使用诸如curses之类的终端模拟器就可以了.它只需要在 linux 上运行,而不是 Mac 或 Windows.

Using terminal emulators like curses would be fine. It only has to run on linux, not Mac or Windows.

这是一个例子:假设我在列表中有以下三个字符串

Here is an example:Say I have the following three strings in a list

['Paul Eden <[email protected]>',
'Eden Jones <[email protected]>',
'Somebody Else <[email protected]>']

我想要一些代码,可以在我输入Eden"后自动完成列表中的前两项,然后让我选择其中一项(全部通过使用键盘的命令行).

I would like some code that will autocomplete the first two items in the list after I type 'Eden' and then allow me to pick one of them (all through the command-line using the keyboard).

推荐答案

我不确定我是否理解问题.您可以使用 readline.clear_history 和 readline.add_history 来设置您想要的可完成字符串,然后使用 control-r 在历史记录中搜索 backword(就像您在 shell 提示符下一样).例如:

I'm not sure I understand the problem. You could use readline.clear_history and readline.add_history to set up the completable strings you want, then control-r to search backword in the history (just as if you were at a shell prompt). For example:

#!/usr/bin/env python

import readline

readline.clear_history()
readline.add_history('foo')
readline.add_history('bar')

while 1:
    print raw_input('> ')

或者,您可以编写自己的完整版本并将适当的密钥绑定到它.此版本使用缓存,以防您的匹配列表很大:

Alternatively, you could write your own completer version and bind the appropriate key to it. This version uses caching in case your match list is huge:

#!/usr/bin/env python

import readline

values = ['Paul Eden <[email protected]>',
          'Eden Jones <[email protected]>',
          'Somebody Else <[email protected]>']
completions = {}

def completer(text, state):
    try:
        matches = completions[text]
    except KeyError:
        matches = [value for value in values
                   if text.upper() in value.upper()]
        completions[text] = matches
    try:
        return matches[state]
    except IndexError:
        return None

readline.set_completer(completer)
readline.parse_and_bind('tab: menu-complete')

while 1:
    a = raw_input('> ')
    print 'said:', a

这篇关于如何做 python 命令行自动补全,但不仅仅是在字符串的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 17:32