【问题标题】:Python argparse with two defaults when the argument is and is not specified当参数是和未指定时,Python argparse 有两个默认值
【发布时间】:2022-01-24 19:20:29
【问题描述】:

对于参数-f,我要了

  1. 在命令中未指定时具有默认值。
  2. 在命令中指定但未指定值时具有另一个默认值
  3. 允许用户为此参数提供单个或多个值

【问题讨论】:

  • parser.add_argument('-f', nargs='?', default=default1, const=default2)。可能会做你想做的事。
  • 这不允许多个值

标签: python argparse


【解决方案1】:

如果您只想为您的选项使用一个值,那么您问题评论中的代码就足够了。

如果您的选项需要多个参数,则不能在 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)

【讨论】:

    猜你喜欢
    • 2019-11-20
    • 2021-10-16
    • 1970-01-01
    • 2015-10-12
    • 2015-09-28
    • 2020-04-26
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多