Howto do python command-line autocompletion but NOT only at the beginning of a string

前端 未结 1 1082
我寻月下人不归
我寻月下人不归 2020-12-28 10:57

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

But, the completion only seems to work at the beginning

相关标签:
1条回答
  • 2020-12-28 11:19

    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 <paul@domain.com>', 
              'Eden Jones <ejones@domain.com>', 
              'Somebody Else <somebody@domain.com>']
    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
    
    0 讨论(0)
提交回复
热议问题