python Argparse库简单示例

Argparse 库:python的命令行解析模块

与Linux的ls用法较类似

简单示例

import argparse

parser = argparse.ArgumentParser(description='calculate X to the power of Y')
group = parser.add_mutually_exclusive_group()
group.add_argument('-v', '--verbose', action='store_true')
group.add_argument('-q', '--quiet', action='store_true')
parser.add_argument('x', type=int, help='the base')
parser.add_argument('y', type=int, help='the exponent')
action='store_true',, choices=[0,1,2]
args = parser.parse_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))

示例结果:

image.png

参考:https://docs.python.org/zh-cn/3/howto/argparse.html

你可能感兴趣的:(python Argparse库简单示例)