Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

python - 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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...