Suppose I have an argparse python script:
import argparse parser = argparse.ArgumentParser() parser.add_argument("--foo", required=True)
Now I want to add another option --bar, which would default to appending "_BAR" to whatever was specified by --foo argument.
My goal:
>>> parser.parse_args(['--foo', 'FOO']) >>> Namespace(foo='FOO', bar="FOO_BAR")
AND
>>> parser.parse_args(['--foo', 'FOO', '--bar', 'BAR']) >>> Namespace(foo='FOO', bar="BAR")
I need something like this:
parser.add_argument("--bar", default=get_optional_foo + "_BAR")
args = parser.parse_args()# Print "Hello" + the user input argument. print('Hello,', args.name) The code above is the most straightforward way to implement argparse . After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments.
The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.
parse_args() returns two values: options, an object containing values for all of your options— e.g. if "--file" takes a single string argument, then options. file will be the filename supplied by the user, or None if the user did not supply that option.
required is a parameter of the ArugmentParser object's function add_argument() . By default, the arguments of type -f or --foo are optional and can be omitted. If a user is required to make an argument, they can set the keyword argument required to True .
I would, as a first try, get this working using an after-argparse function.
def addbar(args): if args.bar is None: args.bar = args.foo+'_BAR'
If this action needs to be reflected in the help
, put it there yourself.
In theory you could write a custom Action
for foo
that would set the value of the bar
value as well. But that requires more familiarity with the Action
class.
I tried a custom Action
that tweaks the default
of the bar
action, but that is tricky. parse_args
uses the defaults right at the start, before it has acted on any of the arguments.
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