How to resolve the help message for the analyzer, and not an error, and exit

I use argparse to handle cmd args, I want, if no arguments are given, then print a help message, but now parsing will throw an error and then exit. my code is:

def main():
    print "in abing/start/main"
    parser = argparse.ArgumentParser(prog="abing")#, usage="%(prog)s <command> [args] [--help]")
    parser.add_argument("-v", "--verbose", action="store_true", default=False, help="show verbose output")

    subparsers = parser.add_subparsers(title="commands")

    bkr_subparser = subparsers.add_parser("beaker", help="beaker inspection")
    bkr_subparser.set_defaults(command=beaker_command)
    bkr_subparser.add_argument("-m", "--max", action="store", default=3, type=int, help="max resubmit count")
    bkr_subparser.add_argument("-g", "--grain", action="store", default="J", choices=["J", "RS", "R", "T", "job", "recipeset", "recipe", "task"], type=str, help="resubmit selection granularity")
    bkr_subparser.add_argument("job_ids", nargs=1, action="store", help="list of job id to be monitored")

    et_subparser = subparsers.add_parser("errata", help="errata inspection")
    et_subparser.set_defaults(command=errata_command)
    et_subparser.add_argument("-w", "--workflows", action="store_true", help="generate workflows for the erratum")
    et_subparser.add_argument("-r", "--run", action="store_true", help="generate workflows, and run for the erratum")
    et_subparser.add_argument("-s", "--start-monitor", action="store_true", help="start monitor the errata system")
    et_subparser.add_argument("-d", "--daemon", action="store_true", help="run monitor into daemon mode")
    et_subparser.add_argument("erratum", action="store", nargs=1, metavar="ERRATUM", help="erratum id")

    if len(sys.argv) == 1:
        parser.print_help()
        return

    args = parser.parse_args()
    args.command(args)

    return

How can i do this? thank.

+5
source share
1 answer

The solution is to subclass argparse.ArgumentParserand override its method error(). In fact, after an error, ArgumentParsercalls its own method error(). Arbitrary analysis of the arguments can then be performed through a subclass instead argparse.ArgumentParser. The function error()is in the source for argparse:

def error(self, message):
    """error(message: string)

    Prints a usage message incorporating the message to stderr and
    exits.

    If you override this in a subclass, it should not return -- it
    should either exit or raise an exception.
    """
    self.print_usage(sys.stderr)
    self.exit(2, '%s: error: %s\n' % (self.prog, message))

, error() , , parse_args() .

: , . , :

: *_command(args) args , .

, , , :

args.command(subparsers, args)  # Instead of args.command(args)

*_command() . :

subparsers.choices['beaker'].print_help()  # or print_usage()

.

*_command():

args.command(subparsers.choices[sys.argv[1]], args)

*_command(subparser, args) subparser.print_help().

+3

All Articles