Python argparse: single-valued argument but allow specified multiple times on command line

StackOverflow https://stackoverflow.com/questions/22676037

  •  22-06-2023
  •  | 
  •  

Domanda

In python argparse, is it possible to declare an argument which is just single-valued, instead a list, but allows being specified multiple times, the latest one overrides the earlier ones?

The use case is, I am writing a Python program that reads command line argument from a ~/.xxxrc file, where .xxxrc file has an command line argument per line. I want to allow user override the value in ~/.xxxrc file through command line. My plan is to implicitly adds an @~/.xxxrc to the beginning of argv before passing it to argparse, so that argparse will reads in the file. Now the problem turns into my question above.

Is it possible to achieve this effect? If not, is there any alternative solution to my use case.

È stato utile?

Soluzione

The argparse module does that by default. Take a look at this example, where we specify the same flag twice, and the last one wins:

import argparse
parser = argparse.ArgumentParser(description='example')
parser.add_argument('-a', '--add')
options = parser.parse_args(['-a', 'foo', '-a', 'bar'])
print 'add = {}'.format(options.add) # output: add = bar

Altri suggerimenti

Yes, you can just create a custom action with an nargs='*' or nargs='+'.

Something like this should work:

class GetLastAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if values:
            setattr(namespace, self.dest, values[-1])


parser = argparse.ArgumentParser()
parser.add_argument('-a', nargs='+', action=GetLastAction)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top