1

I am trying to parse a command line like this

cmd {command [COMMAND_OPTS]}

cmd a {1,2}

cmd b

cmd c

Among the commands{a,b,c}, when the command is "a", there might be a COMMAND_OPTS(choices) for "a", say{1,2}, b or c won't have any arguments. And here is what I tried:

import argparse

if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-cmd', nargs = '+', choices = ['a', 'b', 'c'])
# sub_parser = parser.add_subparsers()
# parse_a = sub_parser.add_parser('a')
# parser_a.add_argument("a", default = "1", choices = ["1", "2"])
args = parser.parse_args()
if args.cmd:
    print args.cmd

How to parse this with Python Argparse? It seems the subparser is not intended for this problem..

Thanks,

2
  • 1
    Please provide a Minimal, Complete, and Verifiable example of the problem you are experiencing. You need to make an attempting at solving this yourself so that we have something to debug. Otherwise, you may need to hire someone to do the job for you. Commented Feb 18, 2016 at 16:28
  • thank you for your tips, I edited my question. Commented Feb 18, 2016 at 16:44

1 Answer 1

3

Put all the commands in the subparsers

parser = argparse.ArgumentParser()
sub_parser = parser.add_subparsers(dest='cmd')
parser_a = sub_parser.add_parser('a')
parser_a.add_argument("a", choices = ["1", "2"])
parser_b = sub_parser.add_parser('b')
parser_c = sub_parser.add_parser('c')
args = parser.parse_args()

args.cmd should end up being one of a,b,c. And if given a is should have a args.a attribute with value '1' or '2'. That argument is required so it doesn't make sense to specify a default.

From an interactive ipython shell:

In [13]: parser.parse_args(['b'])
Out[13]: Namespace(cmd='b')
In [14]: parser.parse_args(['c'])
Out[14]: Namespace(cmd='c')
In [15]: parser.parse_args(['a','1'])
Out[15]: Namespace(a='1', cmd='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.