【问题标题】:Using only one argument in argparse for multiple cases在 argparse 中对多种情况仅使用一个参数
【发布时间】:2018-07-25 22:09:52
【问题描述】:
$ script.py status
$ script.py terminate
$ script.py tail /tmp/some.log

如您所见,该脚本可以执行 3 个任务。最后一个任务需要一个额外的参数(文件的路径)。

我只想使用 add_argument 一次,如下所示。

parser.add_argument("command")

然后检查用户请求了什么命令并基于相同的条件创建条件。如果命令是 tail 我需要访问下一个参数(文件路径)

【问题讨论】:

    标签: python python-2.7 argparse


    【解决方案1】:

    您可能必须为每个命令创建一个sub-parser。如果那些其他命令在某些时候也需要参数,那么它是可扩展的。像这样的:

    import argparse
    
    parser = argparse.ArgumentParser(prog='PROG')
    parser.add_argument('--foo', action='store_true', help='global optional argument')
    subparsers = parser.add_subparsers(dest="command", help='sub-command help')
    
    # create the parser for the "status" command
    parser_status = subparsers.add_parser('status', help='status help')
    
    # create the parser for the "tail" command
    parser_tail = subparsers.add_parser('tail', help='tail help')
    parser_tail.add_argument('path', help='path to log')
    
    print parser.parse_args()
    

    add_subparsers 的 dest 关键字可确保您之后仍然可以获取命令名称,如 here 和文档中所述。

    示例用法:

    $ python script.py status   
    Namespace(command='status', foo=False)
    
    $ python script.py tail /tmp/some.log
    Namespace(command='tail', foo=False, path='/tmp/some.log')
    

    请注意,任何全局参数都需要在命令之前:

    $ python script.py tail /tmp/some.log --foo
    usage: PROG [-h] [--foo] {status,tail} ...
    PROG: error: unrecognized arguments: --foo
    
    $ python script.py --foo tail /tmp/some.log
    Namespace(command='tail', foo=True, path='/tmp/some.log')
    

    【讨论】:

    • 不知道子解析器的概念。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2019-12-19
    • 2022-01-07
    • 2021-12-28
    • 1970-01-01
    • 2016-06-08
    • 2021-10-17
    相关资源
    最近更新 更多