1

I am having some trouble with argparse. My goal is to have the user select one and only one option (-a, -b, -c, etc.) and then the arguments for that option. I'm using subparsers to do this:

parser_iq = subparsers.add_parser('iq', help='iq help')
parser_iq.add_argument("-iq", "--index_query", nargs="+", action=required_length(1,6),type=organize_args, help="Choose an index to query for. Start-date, end-date,  "\
           "csv, json, stdout are all optional")

This is just one of the subparsers I plan to have.

Problem: When running this in the command line:

python3.6 main.py iq "index_name_here"

I get the error that "index_name_here" is unrecognized. I am parsing it like this:

args = parser.parse_args()

I found some problems similar to mine, but they were passing in sys.argv into parse_args(), which was their issue.

How can I make it so that argparse will recognize the arguments passed? Also, is there a way to have only one option passed in at a time? For example:

Correct:

main.py option1 arg1 arg2

Wrong:

main.py option1 option2 arg1 arg2

Thank you!

helloworld95
  • 366
  • 7
  • 17

1 Answers1

2

You have to pass the value like python3.6 main.py -iq "index_name_here" (i.e., use -iq, not iq).

As far as making mutually exclusive arguments, subparsers is, from what I understand, the way to go, but I can't give much in the way of guidance on how to proceed on that.

Edit:

In response to your comment, does the following work:

python3.6 main.py iq -iq "index_name_here"

?

PMende
  • 5,171
  • 2
  • 19
  • 26
  • thanks for the help! When I try running with -iq, it gives me this error: error: invalid choice: 'log4j-*' (choose from 'iq') – helloworld95 Feb 20 '19 at 18:52
  • Yes, iq -iq works! I didn't think about that at all, and it doesn't make much sense to me. Do you know why it runs like this? – helloworld95 Feb 20 '19 at 18:56
  • @helloworld95 When you pass `iq`, python knows to invoke the `parser_iq` parser (because that's the first argument you pass to `add_parser`). This parser has an argument that can be changed by passing an `-iq` or `--index_query` flag along with its associated argument. The documentation isn't the best, but see: https://docs.python.org/3/library/argparse.html – PMende Feb 20 '19 at 19:01
  • According to the docs, its not required to specify both the parser and argument (iq and -iq). >>> parser_a = subparsers.add_parser('a', help='a help') >>> parser_a.add_argument('bar', type=int, help='bar help') >>> parser.parse_args(['a', '12']) Namespace(bar=12, foo=False) It seems like I'm following the doc, but its still not working as I'd like it to. – helloworld95 Feb 20 '19 at 19:24
  • That `bar` argument is a `positional`. Your `-iq` is a flagged (`optionals`) argument. The distinction is fundamental to how `argparse` works. The `subparsers` argument is actually a specialized `positional`. – hpaulj Feb 20 '19 at 21:52