2

The following is an example of a script which uses argparse:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('required')
parser.add_argument('--version', action='store_true')

args = parser.parse_args()
if args.version:
    print('Version: x.y.z')

The script defines a required argument as well as an optional one. Thus the following usage is illegal:

$ python test.py --version
test.py: error: the following arguments are required: required

Is there a way to modify the definition of --version such that either a special action is performed (printing the version number) or that parsing always succeeds when this argument is specified (ignoring missing required arguments)? Similar to the --help flag which doesn't complain about missing arguments but shows more information about the script instead I would like to print a version number when the --version flag is used:

$ python test.py --help
usage: test.py [-h] [--version] required

positional arguments:
  required

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

The desired behavior is:

$ python test.py --version
Version: x.y.z
a_guest
  • 34,165
  • 12
  • 64
  • 118

0 Answers0