In python cmd
module, when I press the TAB button, I get the list of possible commands that are available and that I have defined in my cmd.Cmd
class.
My question is whether it is possible to show a set of commands based on the context like in a Cisco router CLI for instance?
-
What is python `cmd`? – Peter Wood Feb 11 '15 at 11:27
-
@PeterWood may be this https://docs.python.org/2/library/cmd.html – oxfn Feb 11 '15 at 11:30
-
What is the *context*? If *context* is the command to complete, take a look at @oxfn answer. – return42 Feb 11 '15 at 12:01
3 Answers
I don't have any experience with this lib, but doc says
If completion is enabled, completing commands will be done automatically, and completing of commands args is done by calling
complete_foo()
with arguments text, line, begidx, and endidx. text is the string prefix we are attempting to match: all returned matches must begin with it. line is the current input line with leading whitespace removed, begidx and endidx are the beginning and ending indexes of the prefix text, which could be used to provide different completion depending upon which position the argument is in.
So, may be you can implement context based completion in complete_foo
function

- 6,590
- 2
- 26
- 34
I have found an answer to my question. One can use nested interpreters, so a nested interpreter is another interpreter object that will have its own commands, this way each context can be modeled by a nested interpreter. Here is a nice explanation and example:
If you want something like Cisco take a look at ishell,
ishell helps you to easily create an interactive shell for your application. It supports command completion, dynamic arguments, a command history, and chaining of commands.
https://github.com/italorossi/ishell
There's a cisco like cli example at https://github.com/italorossi/ishell/blob/master/examples/cisco.py
PS: I'm the author.

- 68
- 3