Howto do python command-line autocompletion but NOT only at the beginning of a string
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 of strings. If you want to match the middle or end of a string readline doesn't work.
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.
- A good example of the type of autocompletion I would like to have is the type that happens in GMail when you type in the To field. If you type one of your contacts' last name, it will come up just as well as if you typed her first name.
- Some use of the up and down arrows or some other method to select from the matched strings may be needed (and not needed in the case of readline) and that is fine in my case.
- My particular use case is a command-line program that sends emails.
- Specific code examples would be very helpful.
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 <paul@domain.com>',
'Eden Jones <ejones@domain.com>',
'Somebody Else <somebody@domain.com>']
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).
Asked by: Melissa629 | Posted: 27-01-2022
Answer 1
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
Answered by: Adelaide620 | Posted: 28-02-2022
Similar questions
bash - Command-line autocompletion for python -m module
Is it possible to get command-line autocompletion of python -m package.subpackage.module?
This is similar to, but not the same as, python ./package/subpackage/module.py, which does autocomplete the directory and file paths. However with -m, python runs the library's module as a script with the appropriate namespacing and import paths.
I'd like to be able to do ...
bash - Command-line autocompletion for python -m module
Is it possible to get command-line autocompletion of python -m package.subpackage.module?
This is similar to, but not the same as, python ./package/subpackage/module.py, which does autocomplete the directory and file paths. However with -m, python runs the library's module as a script with the appropriate namespacing and import paths.
I'd like to be able to do ...
how to add tab autocompletion in Python 3 command-line program
I'm writing a program looks like this:
while True:
userinput = input()
if ' ' in userinput:
cmd, arg = userinput.spilt()
else:
cmd = userinput
arg = None
match cmd:
case "exit":
exit()
case "hello":
print("hello")
case "hi":
print("hi")
case "remove&...
python - WingIDE no autocompletion for my modules
If anyone using WingIDE for their python dev needs:
For some reason I get auto-completion on all the standard python libraries (like datetime....) but not on my own modules.
So if I create my own class and then import it from another class, I get no auto-completion on it.
Does anyone know why this is?
algorithm - Python type inference for autocompletion
Is it possible to use Ocaml/Haskell algorithm of type inference to suggest better autocompletions for Python?
The idea is to propose autocompletion for example in the following cases:
class A:
def m1(self):
pass
def m2(self):
pass
a = A()
a. <--- suggest here 'm1' and 'm2'
fun1(a)
def fun1(b):
b. <--- suggest here 'm1' and 'm2'
Are there any good startin...
python - Including Bash autocompletion with setuptools
I've got a couple packages in PyPI, and I'd like to include autocompletion features with both of them. How would you check that Bash autocompletion should be installed at all (check for /etc/bash_completion, maybe?), and how would you install it with setup.py (preferably using setuptools)?
Autocompletion in dynamic language IDEs, specifically Python in PyDev
I'm new to Python, with a background in statically typed languages including lots and lots of Java.
I decided on PyDev in eclipse as an IDE after checking features/popularity etc.
I was stunned that auto-complete doesn't seem to work properly for builtins. For example if I try automcomplete on datafile after:
datafile = open(directory+"/"+account, 'r')
datafile.
No useful methods are suggest...
command line - Change how Python Cmd Module handles autocompletion
I have a Cmd console set up to auto-complete card names for a Magic: the Gathering collection management system.
It uses the text parameter to query the database for cards, and uses the results to auto-complete/suggest cards.
However, these cards names have multiple words, and Cmd runs auto-completion from the last space to the end of the line.
For example:
mtgdb> add Mag...
Vim: Good AutoCompletion Plugin for Python and PHP
I use Vim with ctags for development. I found ctags to be very useful in going to definitions, but I don't know a good plugin to make use of ctags for clever auto completion. It seems that the default Vim auto completion is not good. When I write set omnifunc? in Vim, I get this:
omnifunction=pythoncomplete#Complete
I do know about OmniComplete for C++, but I don't know any good plugin for...
autocomplete - How to make python autocompletion display matches?
I have kind of a completer class with an autocompletion function. Simple version:
class Completer:
def __init__(self):
self.words = ["mkdir","mktbl", "help"]
self.prefix = None
def complete(self, prefix, index):
if prefix != self.prefix:
self.matching_words = [w for w in self.words if w.startswith(prefix)]
self.prefix = prefix
else:
...
Python editor with autocompletion function in imported module
is there a python editor has autocompletion function in imported module ?
i think like Jcreator for java function completion and argument hints.
thanks,
Guns
How to fix absent Python autocompletion on object instances in Vim?
I have found a strange behavior in Vim when I attempt to use autocompletion on objects. If I instantiate the objects on a module level, the Vim autocompletion will work on the instance I create:
If I try the same from within a function or class, it is no longer working:
python - Autocompletion in Django + pydev
I am trying to make pydev autocomplete my variables from model data, but for now I have been unable to do it.
I have configured the PYTHONPATH in
Window->Preferences->PyDev->Interpreter - Python
to include both the django folder and my project folder.
Then if I have a model like this:
class Team(models.Model):
name = models.CharField(max_length=5...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python