Mutual exception between groups of arguments

I am trying to implement the following argument dependency using the argparse module: ./prog [-h | [-v schema] file] that the user must pass either -h or the file, if the file is transferred, the user can optionally pass the -v scheme.

What I have now but that doesn't seem to work:

import argparse

parser = argparse.ArgumentParser()
mtx = parser.add_mutually_exclusive_group()
mtx.add_argument('-h', ...)  
grp = mtx.add_argument_group()
grp.add_argument('-v', ...)
grp.add_argument('file', ...)   
args = parser.parse_args()

Looks like you can't add the arg group to the mutex group, or am I missing something?

+2
source share
1 answer

If the -hdefault help means then this is all you need (this help is already excluded)

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file')
parser.add_argument('-s','--schema')
parser.parse_args('-h'.split())  # parser.print_help()

production

usage: stack23951543.py [-h] [-s SCHEMA] file
...

-h - , -x. ,

parser = argparse.ArgumentParser()
parser.add_argument('-s','--schema', default='meaningful default value')
mxg = parser.add_mutually_exclusive_group(required=True)
mxg.add_argument('-x','--xxx', action='store_true')
mxg.add_argument('file', nargs='?')
parser.parse_args('-h'.split())

:

usage: stack23951543.py [-h] [-s SCHEMA] (-x | file)

-x file ( ). -s , , , . -x, -s.

args , , args.file None, args.schema .


( , ):

An argument_group mutually_exclusive_group. . SO (. "Related" ), Python. , , , , parse_args. usage.

An argument_group .

A mutually_exclusive_group usage ( ), parse_args. "" , , .

http://bugs.python.org/issue11588 , "". , "" , , . , , , API. , argparse - " ".

+4

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


All Articles