Source From Here
Question
How can I create an alias for a command in a line-oriented command interpreter implemented using the cmd module?
To create a command, I must implement the do_cmd method. But I have commands with long names (like constraint) and I want to provide aliases (in fact, shortcuts) for these commands (like co). How can I do that? One possibility that came to my mind is to implement the do_alias (like do_co) method and just calling do_cmd (do_constraint) in this method. But this brings me new commands in the help of the CLI.
Is there any other way to achieve this? Or may be is there a way to hide commands from the help output?
HowTo
You can overwrite the default method and search for a suitable command handler (as already suggested by Brian):
Execution output:
How can I create an alias for a command in a line-oriented command interpreter implemented using the cmd module?
To create a command, I must implement the do_cmd method. But I have commands with long names (like constraint) and I want to provide aliases (in fact, shortcuts) for these commands (like co). How can I do that? One possibility that came to my mind is to implement the do_alias (like do_co) method and just calling do_cmd (do_constraint) in this method. But this brings me new commands in the help of the CLI.
Is there any other way to achieve this? Or may be is there a way to hide commands from the help output?
HowTo
You can overwrite the default method and search for a suitable command handler (as already suggested by Brian):
- import cmd
- import sys
- class WithAliasCmd(cmd.Cmd):
- def do_long_cmd_name(self, arg):
- print("Hello world!")
- def default(self, line):
- cmd, arg, line = self.parseline(line)
- func = [getattr(self, n) for n in self.get_names() if n.startswith('do_' + cmd)]
- if func: # maybe check if exactly one or more elements, and tell the user
- func[0](arg)
- elif cmd == "hello": # "hello" is an alias for command long_cmd_name
- return self.do_long_cmd_name(arg)
- def do_bye(self, arg):
- print("Bye")
- return True
- if __name__ == '__main__':
- WithAliasCmd().cmdloop()
沒有留言:
張貼留言