Search code examples
pythoncommand-lineargumentsargparsesubparsers

Argparse not recognizing arguments


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!


Solution

  • 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"

    ?