Split command line into groups

Is it possible to split args in groups in python? Here's an MWE with argparse:

#!/usr/bin/python3

import argparse

parser = argparse.ArgumentParser()

# group 1:
parser.add_argument('-a', '--aa',
                    help = "option a",
                    dest = 'a',
                    action = 'store',
)
parser.add_argument('-b', '--bb',
                    help = "option b",
                    dest = 'b',
                    action = 'store',
)

# group 2:
parser.add_argument('-c', '--cc',
                    help = "option c",
                    dest = 'c',
                    action = 'store',
)
parser.add_argument('-d', '--dd',
                    help = "option d",
                    dest = 'd',
                    action = 'store',
)

# last group:
parser.add_argument('--version', action='version', version='%(prog)s 0.1')


args = parser.parse_args()

      

This gives:

./test02.py -h
usage: test02.py [-h] [-a A] [-b B] [-c C] [-d D] [--version]

optional arguments:
  -h, --help    show this help message and exit
  -a A, --aa A  option a
  -b B, --bb B  option b
  -c C, --cc C  option c
  -d D, --dd D  option d
  --version     show program version number and exit

      

As long as I want:

./test02.py -h
usage: test02.py [-h] [-a A] [-b B] [-c C] [-d D] [--version]

optional arguments:
  -h, --help    show this help message and exit
  --version     show program version number and exit

  group 1:
  -a A, --aa A  option a
  -b B, --bb B  option b

  group 2:
  -c C, --cc C  option c
  -d D, --dd D  option d

      

+3


source to share


1 answer


Since you just want the groups to affect the help screen argument groups

should do the trick: https://docs.python.org/3/library/argparse.html#argument-groups



parser = argparse.ArgumentParser()

group1 = parser.add_argument_group('group1') # can take description as well
group1.add_argument('-a', '--aa',
                    help = "option a",
                    dest = 'a',
                    action = 'store',
)
group1.add_argument('-b', '--bb',
                    help = "option b",
                    dest = 'b',
                    action = 'store',
)

group2 = parser.add_argument_group('group 2')
group2.add_argument('-c', '--cc',
                    help = "option c",
                    dest = 'c',
                    action = 'store',
)
group2.add_argument('-d', '--dd',
                    help = "option d",
                    dest = 'd',
                    action = 'store',
)

      

+4


source







All Articles