Aliases for Commands with the Python CMD Module

How to create an alias for a command in a command line interpreter implemented using cmd module?

To create a command, I have to implement the do_cmd method. But I have commands with long names (e.g. constraint ), and I want to provide aliases (actually shortcuts) for these commands (e.g. co ). How can i do this?

One of the possibilities that occurred to me was to implement the do_alias method (for example, do_co ) and just call do_cmd ( do_constraint ) in this method. But it brings me new teams using the CLI.

Is there any other way to achieve this? Maybe there is a way to hide the commands from the output of help ?

+6
source share
3 answers

You can overwrite the default method and find a suitable command handler (as suggested by Brian ):

 import cmd class WithAliasCmd(cmd.Cmd): 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) 
+5
source

The following solution allows teams with an alias to share one help message. This allows you to save all your aliases in one convenient place for editing, making documentation much easier. It checks user input for an alias dictionary with function values and redefines it as default() (see laziness> and brian ) and do_help() .

Here I made aliases 'c' and 'con' execute do_constraint() , 'q' invoke do_quit() and 'h' invoke do_help() . The bonus of this solution is that 'h q' and 'help quit' print the same message. Documentation for multiple teams with an alias can be maintained in the same docstron.

 import cmd class prompt(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.aliases = { 'c' : self.do_constraint , 'con' : self.do_constraint , 'q' : self.do_quit , 'h' : self.do_help } def do_constraint(self, arg): '''Constrain things.''' print('Constraint complete.') def do_quit(self, arg): '''Exit the program.''' return True def do_help(self, arg): '''List available commands.''' if arg in self.aliases: arg = self.aliases[arg].__name__[3:] cmd.Cmd.do_help(self, arg) def default(self, line): cmd, arg, line = self.parseline(line) if cmd in self.aliases: self.aliases[cmd](arg) else: print("*** Unknown syntax: %s" % line) 
+3
source

The docs mention the default method, which you can override to handle any unknown command. Copy it to the prefix to view a list of commands and invoke them, as you suggest for do_alias.

+1
source

Source: https://habr.com/ru/post/927823/


All Articles