Source From Here
Question
Given:
How do I make at most one of "foo, bar" mandatory: --foo x or --bar y are fine, --foo x --bar y is not?
How-To
I think you are searching for something like mutual exclusion. This way, only foo or bar will be accepted, not both:
* ArgumentParser.add_mutually_exclusive_group(required=False):
For example:
- test.py
Then test it this way:
Question
Given:
- import argparse
- pa = argparse.ArgumentParser()
- pa.add_argument('--foo')
- pa.add_argument('--bar')
How-To
I think you are searching for something like mutual exclusion. This way, only foo or bar will be accepted, not both:
* ArgumentParser.add_mutually_exclusive_group(required=False):
For example:
- test.py
- import argparse
- import argparse
- parser = argparse.ArgumentParser(description='For testing')
- group = parser.add_mutually_exclusive_group(required=True)
- group.add_argument('--foo', "-f",action='store_true', default=False)
- group.add_argument('--bar', "-b",action='store_true', default=False)
- args = parser.parse_args()
- print("foo=%s; bar=%s" % (args.foo, args.bar))
沒有留言:
張貼留言