I am aware of how to setup autocompletion of python objects in the python interpreter (on unix).
I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.
My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).
I do not need it to work on windows or mac, just linux.
(In Python Shell window, you can use TAB key besides the key combination of 'CTRL' and 'space' to invoke the built-in auto-completion feature.) Alternatively, you can choose the "Show Completions" in the main Edit menu to achieve the same as well.
Tab Completion and History Editing. Completion of variable and module names is automatically enabled at interpreter startup so that the Tab key invokes the completion function; it looks at Python statement names, the current local variables, and the available module names.
Simply put, it's a way to manage a program script from outside by typing the script name and the input arguments into the command line prompt when trying to execute that particular script. In Python, command line arguments can be used to: Adjust the operation of a certain program.
Use Python's readline
bindings. For example,
import readline def completer(text, state): options = [i for i in commands if i.startswith(text)] if state < len(options): return options[state] else: return None readline.parse_and_bind("tab: complete") readline.set_completer(completer)
The official module docs aren't much more detailed, see the readline docs for more info.
Follow the cmd documentation and you'll be fine
import cmd addresses = [ '[email protected]', '[email protected]', '[email protected]', ] class MyCmd(cmd.Cmd): def do_send(self, line): pass def complete_send(self, text, line, start_index, end_index): if text: return [ address for address in addresses if address.startswith(text) ] else: return addresses if __name__ == '__main__': my_cmd = MyCmd() my_cmd.cmdloop()
Output for tab -> tab -> send -> tab -> tab -> f -> tab
(Cmd) help send (Cmd) send [email protected] [email protected] [email protected] (Cmd) send [email protected] (Cmd)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With