How to autofill python command line, but not only at the beginning of a line

Python, through this readline binding, allows excellent command line completion (as described here ).

But it seems that only the shutdown works at the beginning of the lines. If you want to align the middle or end of a line, then readline does not work.

I would like to autocomplete strings on the python command line, matching what I'm typing with any of the strings in the list of available strings.

  • A good example of the type of autocomplete that I would like to have is the type that appears in GMail when you type in the To field. If you type one of your last names, it will appear just as if you had typed her name.
  • Some use of the up and down arrows or some other method to select from consistent lines may be necessary (and not required in the case of readline), and this is good in my case.
  • My specific use case is a command line program that sends emails.
  • Specific code examples will be very helpful.

Using terminal emulators like curses would be nice. It should work only on Linux, not on Mac or Windows.

Here is an example: Let's say I have the following three lines in a list

['Paul Eden < paul@domain.com >', 'Eden Jones < ejones@domain.com >', 'Somebody Else < somebody@domain.com >'] 

I need some code that will autocomplete the first two items in the list after entering "Eden", and then let me select one of them (all through the command line using the keyboard).

+6
python command-line linux unix autocomplete
source share
1 answer

I'm not sure I understand the problem. You can use readline.clear_history and readline.add_history to configure the necessary lines, and then control-r to search back in history (exactly the same as if you were on the command line). 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 can write your own extended version and associate the corresponding key with it. This version uses caching if 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 
+10
source share

All Articles