【发布时间】:2016-06-09 10:52:50
【问题描述】:
我想构建一个parser.add_argument(...) 来映射给定参数和我的代码中定义的常量。
假设我有以下内容
import argparse
# Both are the same type
CONST_A = <something>
CONST_B = <otherthing>
parser = argparse.ArgumentParser()
parser.add_argument(...)
# I'd like the following to be true:
parser.parse_args("--foo A".split()).foo == CONST_A
parser.parse_args("--foo B".split()).foo == CONST_B
我可以用什么代替...?
我能用const 做的最好的事情是:
import argparse
# Both are the same type
CONST_A = 10
CONST_B = 20
parser = argparse.ArgumentParser()
status_group = parser.add_mutually_exclusive_group(required=True)
status_group.add_argument("-a", const=CONST_A, action='store_const')
status_group.add_argument("-b", const=CONST_B, action='store_const')
# I'd like the following to be true:
print parser.parse_args("-a".split()).a == CONST_A # True
print parser.parse_args("-b".split()).b == CONST_B # True
请注意,常量被保存到两个不同的属性 a 和 b,女巫不适合我:(
【问题讨论】:
-
您是否执行了
help(argparse)或查看了文档? (docs.python.org/3/library/argparse.html) 我现在第一次研究它。 -
我有,但是对于初学者来说有点毛骨悚然。顺便说一句,我正在编写 python2 代码。
-
add_argument有const和default参数。试验一下。 -
@Evert 我可以用
const和action="store_const"做的最好的事情是将我的常量映射到返回的命名空间的两个不同属性中。
标签: python python-2.7 argparse