如何让解析器打印帮助消息而不是错误并退出

发布于 2024-10-09 20:43:32 字数 1806 浏览 3 评论 0原文

我正在使用 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

我该怎么做? 谢谢。

I am using argparse to handle cmd args, I wanna if there is no args specified, then print the help message, but now the parse will output a 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 that?
thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

∞梦里开花 2024-10-16 20:43:32

解决方案包括子类化 argparse.ArgumentParser 并重新定义其 error() 方法。事实上,出现错误时,ArgumentParser 会调用其 error() 方法。然后可以通过子类而不是 argparse.ArgumentParser 来执行自定义参数解析。在 argparse 的源代码中找到了模型 error() 函数:

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()

A solution consists in subclassing argparse.ArgumentParser and redefining its error() method. In fact, upon error, ArgumentParser calls its error() method. The custom argument parsing can then be performed through the subclass instead of argparse.ArgumentParser. A model error() function is found 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))

It is for instance possible to raise an exception in error(), instead of printing a message, so that the code calling parse_args() takes charge of problems with the user parameters.

Original answer: according to the clarification in the comments, the following does not work. However, it provides a mechanism for accessing help messages from the sub-command functions:

You almost have it: in each of your *_command(args) functions, you can test the size of args and print an error message if there are not enough arguments.

If you want to use the automatically generated help, in your command functions, you can get it by passing the subparsers to each command, like so:

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

Each *_command() function should then simply take two arguments instead of one. The automatically generated help is accessible through:

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

for instance.

You could alternatively choose to directly pass the particular subparser to each sub-command routine *_command():

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

and then, in each *_command(subparser, args), print the help with subparser.print_help().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文