使用argparse读取默认参数
当你使用像这样的 argparse 时:
parser.add_argument("-option1", type=int, nargs=1, default=1, choices=xrange(1, 10), help="option 1 message")
如果没有传入参数,args.option1 是一个整数。如果传入了参数,args.option 是一个列表。
这就意味着我必须使用 args.option1 或者 args.option1[0]。有没有办法避免这样做呢?
2 个回答
1
你会得到一个列表,因为你在设置参数时用了 nargs=1
。这个在文档中也有说明:
注意,
nargs=1
会生成一个包含一个项目的列表。这和默认情况不同,默认情况下,项目会单独返回。
如果你去掉 nargs=1
,那么它应该会像你想要的那样单独返回这个项目(如果有给出参数的话,不然就会返回 default
的值)。如果你想让这个数量变成可选的(也就是说,允许 -option1
后面不跟参数),可以使用 nargs='?'
,并把 const
设置为这个情况下的默认值。
2
如果你把 nargs
设置为一个整数,那么当你在命令行中指定参数时,它总是会变成一个列表。你也可以用 '?'
来代替,这样它就可以是一个单独的值 或者 默认值:
parser.add_argument(
"-option1", type=int, nargs='?', default=1,
choices=xrange(1, 10), help="option 1 message")
来自 nargs
的文档:
N
(一个整数)。从命令行获取N
个参数会聚集成一个列表。[...]
'?'
。如果可能的话,会从命令行中获取一个参数,并作为一个单独的项目返回。如果没有命令行参数,则会返回默认值。
我强调一下。你可能还想设置 const
,以防有人在命令行中只使用 仅仅 -option1
而没有后面的值;如果没有 const
,那么值会被设置为 None
。只需将其设置为与默认值相同的值:
parser.add_argument(
"-option1", type=int, nargs='?', default=1, const=1,
choices=xrange(1, 10), help="option 1 message")
另一种选择是不设置 nargs
:
parser.add_argument(
"-option1", type=int, default=1,
choices=xrange(1, 10), help="option 1 message")
这通常意味着几乎和 nargs='?'
一样:
如果没有提供
nargs
这个关键字参数,那么消耗的参数数量由动作决定。通常这意味着会消耗一个命令行参数,并返回一个单独的项目(而不是列表)。
不同之处在于,命令行中不允许出现空的 -option1
参数;不需要设置 const
。
演示:
>>> from argparse import ArgumentParser
>>> parser = ArgumentParser()
>>> parser.add_argument(
... "-option1", type=int, nargs='?', default=1, const=1,
... choices=xrange(1, 10), help="option 1 message")
_StoreAction(option_strings=['-option1'], dest='option1', nargs='?', const=1, default=1, type=<type 'int'>, choices=xrange(1, 10), help='option 1 message', metavar=None)
>>> parser.parse_args(['-option1', '4']) # option with argument
Namespace(option1=4)
>>> parser.parse_args(['-option1']) # option with *no* argument
Namespace(option1=1)
>>> parser.parse_args([]) # option not specified
Namespace(option1=1)
>>> parser = ArgumentParser()
>>> parser.add_argument(
... "-option1", type=int, default=1,
... choices=xrange(1, 10), help="option 1 message")
_StoreAction(option_strings=['-option1'], dest='option1', nargs=None, const=None, default=1, type=<type 'int'>, choices=xrange(1, 10), help='option 1 message', metavar=None)
>>> parser.parse_args(['-option1', '4']) # option with argument
Namespace(option1=4)
>>> parser.parse_args([]) # option not specified
Namespace(option1=1)
>>> parser.parse_args(['-option1']) # option with *no* argument
usage: [-h] [-option1 {1,2,3,4,5,6,7,8,9}]
: error: argument -option1: expected one argument