argparse:位置参数的默认设置不起作用?

Gho*_*ica 6 python argparse

我有:

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()
Run Code Online (Sandbox Code Playgroud)

但是当我跑步时: python test.py我得到:

usage: test.py [-h] {dump,delete,update,set}
test.py: error: too few arguments
Run Code Online (Sandbox Code Playgroud)

也许我今天只是瞎子;但我不知道我的输入应该有什么问题。还是用argparse根本不可能?

小智 8

为了使default关键字参数起作用,您必须添加nargs='*'如下内容:

parser.add_argument("command",
        help="the command to be executed",
        choices=["dump", "delete", "update", "set"],
        nargs='?',
        default="set"
    )
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参见https://docs.python.org/2/library/argparse.html#default:)

通过OP编辑:nargs='*'允许输入多个命令。因此更改nargs='?'为我正在寻找要输入的一个命令。

  • 我认为在OP的情况下最好使用`nargs='?'` (2认同)