0

I have the following test code:

import argparse
myparser = argparse.ArgumentParser(prog='test')
myparser.add_argument('mode', choices=['A', 'B'])
subparsers = myparser.add_subparsers()
a_parser = subparsers.add_parser('A')
b_parser = subparsers.add_parser('B')
a_parser.add_argument('frog',action='store')
b_parser.add_argument('toad',action='store')
print(myparser)
try:
    args = myparser.parse_args(['A', 'frogname'])
    print(args)
except ArgumentError as ae:
    print(ae)

When I run it I get the following:

ArgumentParser(prog='test', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
usage: test [-h] {A,B} {A,B} ...
test: error: invalid choice: 'frogname' (choose from 'A', 'B')

I'm not sure why I'm getting multiple copies of the 'mode' argument or why my subparsers are being ignored.

1 Answer 1

2

If you are using mode to try to select the subparser, you don't need to do that. That's part of what add_parser() does for you.

myparser = argparse.ArgumentParser(prog='test')
# myparser.add_argument('mode', choices=['A', 'B'])  # Don't think you need this
subparsers = myparser.add_subparsers()
a_parser = subparsers.add_parser('A')
b_parser = subparsers.add_parser('B')
a_parser.add_argument('frog',action='store')
b_parser.add_argument('toad',action='store')

args = myparser.parse_args(['A', 'frogname'])
print(args)
>>> Namespace(frog='frogname')

If mode is something separate that you want to set in addition to choosing the subparser, you need to pass that argument separately

myparser = argparse.ArgumentParser(prog='test')
myparser.add_argument('mode', choices=['A', 'B'])
subparsers = myparser.add_subparsers()
a_parser = subparsers.add_parser('A')
b_parser = subparsers.add_parser('B')
a_parser.add_argument('frog',action='store')
b_parser.add_argument('toad',action='store')

args = myparser.parse_args(['A', 'A', 'frogname'])
print(args)
>>> Namespace(frog='frogname', mode='A')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.