I have googled this around but can't seem to find if this question has been asked already. I want to have a value (say "blah") to be always present for a list option, plus additional arguments if they are provided.
e.g.
import argparse
args = argparse.ArgumentParser()
args.add_argument("--foo", nargs="+")
args = args.parse_args(["--foo", "bar1", "bar2", "bar3"])
args.foo.append("blah")
print args.foo
['bar1', 'bar2', 'bar3', 'blah']
Inspired by python argparse - optional append argument with choices, this may be a little overkill, but it may be useful for others that want to use sets and add constant values to options:
import argparse
DEFAULT = set(['blah'])
class DefaultSet(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
default_set = DEFAULT
if values:
default_set.update(v)
setattr(namespace, self.dest, default_set)
args = argparse.ArgumentParser()
args.add_argument("--foo", default=DEFAULT, action=DefaultSet,nargs="+")
args = args.parse_args(["--foo", "bar1", "bar2", "bar3"])
print args.foo
set(['bar1', 'blah', 'bar3', 'bar2'])
The only problem is that the custom action is only called when foo is specified with at least 1 argument. That is why I had to include DEFAULT in add_argument definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With