【发布时间】:2022-01-24 19:20:29
【问题描述】:
对于参数-f,我要了
- 在命令中未指定时具有默认值。
- 在命令中指定但未指定值时具有另一个默认值
- 允许用户为此参数提供单个或多个值
【问题讨论】:
-
parser.add_argument('-f', nargs='?', default=default1, const=default2)。可能会做你想做的事。 -
这不允许多个值
对于参数-f,我要了
【问题讨论】:
parser.add_argument('-f', nargs='?', default=default1, const=default2)。可能会做你想做的事。
如果您只想为您的选项使用一个值,那么您问题评论中的代码就足够了。
如果您的选项需要多个参数,则不能在 add_argument 中使用 const(nargs 需要'?'),而是可以将 Action 类子类化(在 argparse 中找到):
class FAction(argparse.Action):
#The default to use in case the option is provided by
#the user, you can make it local to __call__
__default2 = 'def2'
#__call__ is called if the user provided the option
def __call__(self, parser, namespace, values, option_string=None):
#If the option f is provided with no arguments
#then use __default2 which is the second default
#if values length is 0< then use what the user
#has provided
if len(values) == 0:
values = self.__default2
setattr(namespace, self.dest, values)
parser = argparse.ArgumentParser(description='Program arguments')
parser.add_argument('-f', default='def', nargs='*', action=FAction)
args = parser.parse_args()
print(args.f)
【讨论】: