A direct way would be to create an argparse parser and line.split() inside your function, expect ing SystemExit if invalid arguments are provided ( parse_args() calls sys.exit() when invalid arguments are found).
class TestInterface(cmd.Cmd): __test1_parser = argparse.ArgumentParser(prog="test1") __test1_parser.add_argument('--bar', help="bar help") def help_test1(self): self.__test1_parser.print_help() def do_test1(self, line): try: parsed = self.__test1_parser.parse_args(line.split()) except SystemExit: return print("Test1...") print(parsed)
If invalid arguments are parse_args() , parse_args() will print errors and the program will return to the interface without exiting.
(Cmd) test1 --unk usage: test1 [-h] [--bar BAR] test1: error: unrecognized arguments: --unk (Cmd)
Everything else should work just like a normal argparse use argparse , also supporting all cmd functions (help messages, list of functions, etc.)
Source: https://groups.google.com/forum/#!topic/argparse-users/7QRPlG97cak
Another way to simplify the setup above is to use the decorator below:
class ArgparseCmdWrapper: def __init__(self, parser): """Init decorator with an argparse parser to be used in parsing cmd-line options""" self.parser = parser self.help_msg = "" def __call__(self, f): """Decorate 'f' to parse 'line' and pass options to decorated function""" if not self.parser:
It simplifies the definition of additional commands, where they take the additional parameter parsed , which contains the result of successful parse_args() . If there are any invalid arguments, the function is never entered, everything is processed by the decorator.
__test2_parser = argparse.ArgumentParser(prog="test2") __test2_parser.add_argument('--foo', help="foo help") @WrapperCmdLineArgParser(parser=__test2_parser) def do_test2(self, line, parsed): print("Test2...") print(parsed)
Everything works as a source example, including argparse generated help messages - without having to define the help_command() function.
Source: https://codereview.stackexchange.com/questions/134333/using-argparse-module-within-cmd-interface