The code file hacker_argparse.py is as follows:
import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y", epilog="And
that's how you'd foo a bar")
group = parser.add_mutually_exclusive_group()
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument('-v','--version', action='version', version='%(prog)s 2.0')
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
# print(args)
answer = args.x ** args.y
if args.quiet:
print(answer)
elif args.verbose:
print("{} to the power {} equals {}".format(args.x, args.y, answer))
else:
print("{}^{} == {}".format(args.x, args.y, answer))
Execute on the command line: python3 hacker_argparse.py
The results are as follows:
$ python3 hacker_argparse.py -h
usage: hacker_argparse.py [-h] [-q] [-V] [-v] x y
calculate X to the power of Y
positional arguments:
x the base
y the exponent
optional arguments:
-h, --help show this help message and exit
-q, --quiet
-V, --version show program's version number and exit
-v, --verbose increase output verbosity
And that's how you'd foo a bar