Python 中的 argparse 中的元变量和动作是什么意思? [英] What does metavar and action mean in argparse in Python?

查看:22
本文介绍了Python 中的 argparse 中的元变量和动作是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 argparse 模块.我被元变量和动作的含义卡住了

<预><代码>>>>parser.add_argument('整数', metavar='N', type=int, nargs='+',... help='累加器的整数')>>>parser.add_argument('--sum', dest='accumulate', action='store_const',... const=sum,默认=max,... help='sum the integers (default: find the max)')

我可能错过了,但从我读到的内容来看,我找不到 metavar 的定义和action (action="store_const", etc).它们实际上是什么意思?

解决方案

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

<预><代码>>>>解析器 = argparse.ArgumentParser()>>>parser.add_argument('--foo')>>>parser.add_argument('bar')>>>parser.parse_args('X --foo Y'.split())命名空间(bar='X', foo='Y')>>>parser.print_help()用法:[-h] [--foo FOO] bar...

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

I am reading through argparse module. I got stuck as what to metavar and action means

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

I might have missed but from what I read, I could not find definitions for metavar and action (action="store_const", etc). what do they actually mean?

解决方案

metavar is used in help messages in a place of an expected argument. See FOO is a default metavar here:

>>> 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 defines how to handle command-line arguments: store it as a constant, append into a list, store a boolean value etc. There are several built-in actions available, plus it's easy to write a custom one.

这篇关于Python 中的 argparse 中的元变量和动作是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆