Skip to content Skip to sidebar Skip to footer

How To Code Argparse Combinational Options In Python

I have been troubled with this small piece of activity to be completed. I did do some experiment, but was not able to achieve the result. Requirement: test2.py [-c/-v] -f Usag

Solution 1:

Set the filename to be a positional argument, and let argparse set its own usage message:

$ python so.py --help
usage: so.py [-h] [-c Package1 Package2 | -v Package] outFileName

The filename should be positional, and you should let argparse write its own usage message.

Code

#!/usr/bin/python

import sys
import argparse

def main():
    description='Package Compare/Verifier tool.'
    parser = argparse.ArgumentParser(description=description,
                                     epilog='--compare and --verify are mutually exclusive')

    parser.add_argument('f',action='store',nargs=1,
                        help='File Name where result is stored.',
                        metavar="outFileName")

    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument('-c','--compare',action='store',nargs=2,dest='packageInfo',help='Compare two packages.',metavar=("Package1","Package2"))
    group.add_argument('-v','--verify',action='store',nargs=1,dest='packageName',help='Verify Content of package.',metavar='Package')

    args = parser.parse_args()

if __name__ == "__main__":
    main()

Help message

$ python so.py --help
usage: so.py [-h] [-c Package1 Package2 |-v Package] outFileName

Package Compare/Verifier tool.

positional arguments:
  outFileName           File Name whereresultis stored.

optional arguments:
  -h, --help            show this help message and exit-c Package1 Package2, --compare Package1 Package2
                        Compare two packages.
  -v Package, --verify Package
                        Verify Content of package.

--compare and --verify are mutually exclusive

Solution 2:

What exact output are you looking for? I am not aware of any standard syntax for denoting mutual exclusitivity in a --help output, and it would likely be confusing for your users if you made one up. Also I assume that argparse doesn't support a syntax for it (since if it did, it would already be working).

I suggest you keep it simple and just explain to your users the mutual exclusion in the help for each of the arguments. So change their help strings as follows:

-c Package1 Package2, --compare Package1 Package2
                      Compare two packages (may not be used with -v).
-v Package, --verify Package
                      Verify Content of package (may not be used with -c).

That is extremely obvious and reasonably concise.

Another alternative would be just to not mention it, and have the user discover that they are mutually exclusive by trying to use them simultaneously (argparse automatically generates a user-friendly error such as "PROG: error: argument -c: not allowed with argument -v").

Solution 3:

I think the basic complaint is with the default positional arguments and optional arguements group names. In the help, optional arguments means: requires a flag like -f or --file; positional arguments means it is identified by position. With default values, positionals are indeed required, and optionals are indeed optional (not required). But the user can change that with a required attribute, giving rise to confusing terminology.

A way around this is to define your own argument groups. These groups affect the layout of the help, but have no effect on parsing. They also don't affect the usage line.

def main():
    description='Package Compare/Verifier tool.'
    parser = argparse.ArgumentParser(usage=None,description=description)

    maingroup = parser.add_argument_group(title='required')
    maingroup.add_argument('-f','--file',nargs=1,dest='outFileName',help='File Name where result is stored.',metavar="outFileName",required=True)
    exgroup = parser.add_argument_group(title='one or the other')

    group = exgroup.add_mutually_exclusive_group(required=True)
    group.add_argument('-c','--compare',nargs=2,dest='packageInfo',help='Compare two packages.',metavar=("Package1","Package2"))
    group.add_argument('-v','--verify',nargs=1,dest='packageName',help='Verify Content of package.',metavar='Package')
    args = parser.parse_args()

produces:

usage: stack5603364.py [-h] -f outFileName (-c Package1 Package2 | -v Package)

Package Compare/Verifier tool.

optional arguments:
  -h, --help            show this help message andexitrequired:
  -f outFileName, --file outFileName
                        File Name where result is stored.

one or the other:
  -c Package1 Package2, --compare Package1 Package2
                        Compare two packages.
  -v Package, --verify Package
                        Verify Content of package.

The mutually_exclusive_group affects only the usage line.

(-c Package1 Package2 |-v Package)

displays a group where one of the choices is required.

[-c Package1 Package2 | -v Package]

would be an optional group. [] are used to mark optional (in the 'not required' sense) arguments. Note how -h continues to be labeled.

http://bugs.python.org/issue9694 is the related Python issue, where the argparse author favors this argument_group approach.

Post a Comment for "How To Code Argparse Combinational Options In Python"