如何让解析器打印帮助消息而不是error和exi

2024-04-29 01:52:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用argparse来处理cmd参数,如果没有指定参数,则打印帮助消息,但现在解析将输出错误,然后退出。 我的代码是:

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

我怎么能做到呢? 谢谢。在


Tags: storeaddtrueparserhelpargsactionargument
1条回答
网友
1楼 · 发布于 2024-04-29 01:52:06

解决方案包括子类化argparse.ArgumentParser并重新定义其error()方法。事实上,一旦出错,ArgumentParser将调用其error()方法。然后可以通过子类而不是argparse.ArgumentParser执行自定义参数解析。模型error()函数在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的大小,如果没有足够的参数,则打印一条错误消息。在

如果要使用自动生成的帮助,在命令函数中,可以通过将子参数传递给每个命令来获取,如下所示:

^{pr2}$

每个*_command()函数应该只接受两个参数而不是一个参数。自动生成的帮助可通过以下方式访问:

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

例如。在

您也可以选择直接将特定的子parser传递给每个子命令例程*_command()

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

然后,在每个*_command(subparser, args)中,用subparser.print_help()打印帮助。在

相关问题 更多 >