我有:
from argparse import ArgumentParser
parser = ArgumentParser(description='Test')
parser.add_argument("command",
help="the command to be executed",
choices=["dump", "delete", "update", "set"],
default="set")
parser.parse_args()
但是当我运行:python test.py
我得到:
usage: test.py [-h] {dump,delete,update,set}
test.py: error: too few arguments
也许我今天只是瞎了眼;但我不知道我的输入有什么问题。或者这对于 argparse 来说根本不可能吗?
最佳答案
要使 default
关键字参数生效,您必须像下面这样添加 nargs='*'
:
parser.add_argument("command",
help="the command to be executed",
choices=["dump", "delete", "update", "set"],
nargs='?',
default="set"
)
参见 https://docs.python.org/2/library/argparse.html#default获取更多信息:)
由 OP 编辑:nargs='*'
允许输入多个命令。因此更改为 nargs='?'
,因为我正在寻找要输入的exactly one 命令。
关于python - argparse:位置参数的默认值不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43391084/