Argparse mutally excludes subgrouping

Currently, 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 to do is the following:

  • -q should be mutually excluded from -d
  • and --jsonshould only go with-q

How will this go? 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()

He currently rejects -qwith --json:

python ir.py --json -q mcpip1
usage: ir.py [-h] [-q  | --json | -d ]

ir.py: error: argument -q: not allowed with argument --json
+4
source share
2 answers

-qand -dare not really parameters (presumably one of them is necessary); they are subcommands, so you should use subparser function argparseto create two sub-commands queryand indexand associate --jsononly with the sub-command query.

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 general program is available using

ir.py -h

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

-

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

--json parser, group, , . , , .

parse_args. , mutually_exclusvie_groups. , API .

, subparsers .

, usage? --json -q ?

0

Source: https://habr.com/ru/post/1543014/


All Articles