代码之家  ›  专栏  ›  技术社区  ›  eagertoLearn

metavar和action在Python中的argparse中意味着什么?

  •  111
  • eagertoLearn  · 技术社区  · 11 年前

    我正在通读 argparse 单元我被元变量和行动的含义所困扰

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

    我可能错过了,但从我读到的内容来看,我找不到 metavar action (action="store_const", etc) 。它们到底是什么意思?

    2 回复  |  直到 6 年前
        1
  •  75
  •   Michael come lately PhiLho    5 年前

    Metavar公司: 它为帮助消息中的可选参数提供了不同的名称。在中为metavar关键字参数提供一个值 add_argument() .

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', metavar='YYY')
    >>> parser.add_argument('bar', metavar='XXX')
    >>> parser.parse_args('X --foo Y'.split())
    Namespace(bar='X', foo='Y')
    >>> parser.print_help()
    usage:  [-h] [--foo YYY] XXX
    
    positional arguments:
      XXX
    
    optional arguments:
      -h, --help  show this help message and exit
      --foo YYY
    

    参考文献: http://www.usatlas.bnl.gov/~caballer/files/argparse/add_argument.html

    行动: 参数可以触发不同的操作,由操作参数指定 添加参数() 。当遇到参数时,可以触发六个内置操作:

    1. store :在可选地将值转换为其他类型之后,保存该值。如果没有明确指定,则这是默认的操作。

    2. store_true / store_false :保存适当的布尔值。

    3. store_const :保存定义为参数规范一部分的值,而不是来自正在分析的参数的值。这通常用于实现非布尔的命令行标志。

    4. append :将值保存到列表中。如果参数重复,则会保存多个值。

    5. append_const :将参数规范中定义的值保存到列表中。

    6. version :打印有关程序的版本详细信息,然后退出。

    参考文献: http://bioportal.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html

        2
  •  56
  •   alecxe    11 年前

    metavar 在帮助消息中用于预期参数的位置。看见 FOO 是默认值 metavar 在这里:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo')
    >>> parser.add_argument('bar')
    >>> parser.parse_args('X --foo Y'.split())
    Namespace(bar='X', foo='Y')
    >>> parser.print_help()
    usage:  [-h] [--foo FOO] bar
    ...
    

    action 定义了如何处理命令行参数:将其存储为常量,附加到列表中,存储布尔值等。有几个内置操作可用,而且编写自定义操作很容易。