Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse default option based on another option

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") 
like image 562
paroxyzm Avatar asked Nov 18 '13 12:11

paroxyzm


People also ask

What does Argparse ArgumentParser ()?

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.

What is action Store_true in Argparse?

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.

What does parse_args return?

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.

How do you make an argument mandatory in Python?

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 .


1 Answers

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.

like image 95
hpaulj Avatar answered Sep 23 '22 12:09

hpaulj