如何用python编写一个命令行程序

 阅读大约需要1分钟

代码文件hacker_argparse.py如下:

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))

在命令行下执行: python3 hacker_argparse.py

结果如下:

$ 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