• 学习python argparse库


    1. 生成parser

    import argparse
    parser = argparse.ArgumentParser(description='Process some integers.')
    

    2. 添加参数设置

    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', 										
                        action='store_const',
                        const=sum, default=max,
                        help='sum the integers (default: find the max)')
    

    3. 解析参数

    args = parser.parse_args()
    # args is the populated namespace.
    print(args.accumulate(args.integers)) 
    

    注意: 参考官网

    • action 可取'store'(默认), 'store_const' , 'store_true' and 'store_false', 'append', 'append_const', 'count', 'help', 'version'
    • nargs 可取N (an integer), '?', '+', '*', argparse.REMAINDER
    • type 指定对应参数值的类型
    • choices 指定可供选择的范围
    • required 指定是否必须提供
    • metavar 用于参数提示
    • dest 指定命名空间中参数对应的key

    即:

    ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
    Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:

    name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.

    action - The basic type of action to be taken when this argument is encountered at the command line.

    nargs - The number of command-line arguments that should be consumed.

    const - A constant value required by some action and nargs selections.

    default - The value produced if the argument is absent from the command line.

    type - The type to which the command-line argument should be converted.

    choices - A container of the allowable values for the argument.

    required - Whether or not the command-line option may be omitted (optionals only).

    help - A brief description of what the argument does.

    metavar - A name for the argument in usage messages.

    dest - The name of the attribute to be added to the object returned by parse_args().

  • 相关阅读:
    产品经理之PRD详解(非原创)
    编写代码的「八荣八耻」- 以开关上线为荣,以自信编码为耻
    安装社区版git仓库
    【干货分享】大话团队的GIT分支策略进化史
    Android IPC机制(一)开启多进程
    使用adb命令通过IP地址连接手机
    一篇文章了解Github和Git教程-AndroidStudio上传Github教程
    sublime实现markdown浏览器预览
    idea上maven使用心得(三)——用pom.xml添加jar包
    idea解决Maven jar依赖冲突(四)
  • 原文地址:https://www.cnblogs.com/lyg-blog/p/11450468.html
Copyright © 2020-2023  润新知