Skip to content

argparse : support "single occurence" arguments #128301

@WasfiJ

Description

@WasfiJ

Feature or enhancement

Proposal:

Hello,

Just finished writing a little gadget to move/rename files inside a given bucket/folder/ on S3 (AWS).
It wouldn't make sense to pass multiple "-b bucket" to my program.
Sure, I can count such args gathered in an Action.dest and emit an error, but it would be nice to express such requirement and have argparse handle it.

Here is an example modification implementing such control in _ExtendAction that worked for me :

  • check len(items) for error condition
  • add user error message, which is necessarily more helpful that a generic "used more than once" (optional)
class UseOnceExtendAction(argparse._ExtendAction):

  def __init__( self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None,
                required=False, help=None, metavar=None, deprecated=False, errmsg=None ) :
    super(argparse._ExtendAction, self).__init__(
      option_strings=option_strings, dest=dest, nargs=nargs, const=const, default=default, type=type,
      choices=choices, required=required, help=help, metavar=metavar, deprecated=deprecated )
    self.errmsg = errmsg
  
  def __call__(self, parser, namespace, values, option_string=None):
    items = getattr(namespace, self.dest, None)
    if values and hasattr(items, "__iter__") :
      i = -1
      if   self.default == None and len(items) == 1 : i = 0
      elif self.default != None and len(items) == 2 : i = 1
      if i >= 0 :
        if self.errmsg : self.errmsg = '\n\n  ' + self.errmsg.strip() + '\n'
        else : self.errmsg = '\n' 
        self.errmsg = ' :\n\n     ' + option_string+' ' + items[i] +'\n     '+option_string+' '+ values[0] + self.errmsg
        raise argparse.ArgumentError(self, argparse._('used more than once%s') %self.errmsg )
    items = argparse._copy_items(items)
    items.extend(values)
    setattr(namespace, self.dest, items)

# Use : 
parser.add_argument('-b', '--bucket', required=True, nargs=1, action=UseOnceExtendAction, metavar="<Bucket>", 
  dest='bucket', help='Set S3 bucket.', errmsg='\n  Please provide one single S3 bucket !\n' )

Effect :

$ python3.13 -u 'd:\dev\aws_mass_mv.py' -b bucket1 -b bucket2 

  Usage : aws_mass_mv.py -b <Bucket> -r <root_folder> -i <input_file> [<input_file> ...] [-s <char>]
                         [-w | --overwrite | --clobber ] [-k <max_age>] [-o <log_file>] [-h] [-v]

Error : -b/--bucket used more than once :

     -b bucket1
     -b bucket2

  Please provide one single S3 bucket !

Also, an other suggestion : added a few line breaks in ArgumentParser.error() to make for a clearer message with prominent error indication :

  def error(self, message):  
    try : sys.stderr.write('\n'+self.format_usage()) # formatter.add_usage(self.usage, .. ,'  Usage : ')
    except (AttributeError, OSError) : pass
    self.exit(2, argparse._('\nError : %s\n') % message)

Peace.

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions