Argparse mutally exclusive by subgrouping
Question: Currently the argparse of my code gives the following:

    
    
    usage: ir.py [-h] [-q  | --json | -d ]
    
    Some text
    
    optional arguments:
      -h, --help            show this help message and exit
      -q                    gene query terms (e.g. mcpip1)
      --json                output in JSON format, use only with -q
      -d , --file_to_index  file to index 
    

What I want it to do is the following:

  1. `-q` should be mutually exclusive from `-d`
  2. and `--json` should only go with `-q`

What's the way go go about it? This is my argparse code:

    
    
    parser = argparse.ArgumentParser(description='''Some text''')
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-q",help="gene query terms (e.g. mcpip1)",metavar="",type=str)
    group.add_argument("--json", help="output in JSON format, use only with -q", action="store_true")
    group.add_argument("-d","--file_to_index", help="file to index",metavar="",type=str)
    args = parser.parse_args()
    

It currently rejects `-q` with `--json`:

    
    
    python ir.py --json -q mcpip1
    usage: ir.py [-h] [-q  | --json | -d ]
    
    ir.py: error: argument -q: not allowed with argument --json
    


Answer: `-q` and `-d` aren't really options (presumably, one them is required);
they're subcommands, so you should use the subparser feature of `argparse` to
create two subcommands `query` and `index`, and associate `--json` only with
the `query` subcommand.

    
    
    import argparse
    parser = argparse.ArgumentParser(description='''Some text''')
    subparsers = parser.add_subparsers()
    
    query_p = subparsers.add_parser("query", help="Query with a list of terms")
    query_p.add_argument("terms")
    query_p.add_argument("--json", help="output in JSON format, use only with -q", action="store_true")
    
    index_p = subparsers.add_parser("index", help="index a file")
    index_p.add_argument("indexfile", help="file to index")
    
    args = parser.parse_args()
    

Help for the overall program is available with

    
    
    ir.py -h
    

Help for each subcommand is displayed separately

    
    
    ir.py query -h
    ir.py index -h
    

Usage would be something like

    
    
    ir.py query "list of terms"
    ir.py query --json "list of terms"
    ir.py index somefile.ext
    

