主要参考了https://www.cnblogs.com/yymn/p/8056487.html by 菜鸡一枚
demo1
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('echo')
args = parser.parse_args()
print(args.echo)
python a.py x
就会输出x,但是x必须有,x可以是字符串或者数字等等.如果写成’-echo’那么不加x也行,这样会输出none
demo2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v","--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
print("verbosity turned on")
- python a.py 无输出
- python a.py -v 报错
- python a.py -v 3 输出verbosity turned on
如果想让python a.py -v
也输出verbosity turned on可以将第三行改成:
parser.add_argument("-v","--verbosity", help="increase output verbosity", action='store_true')
demo3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('x', type=int, help='the base')
args = parser.parse_args()
print(args.x ** 2)
demo4
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('square', type=int, help='square')
parser.add_argument('-v', '--ver',type=int, choices=[1, 2, 3], help='v')
args = parser.parse_args()
if args.ver == 1:
print('the square of {} equals {}'.format(args.square, args.square**2))
elif args.ver == 2:
print('{}^2 equals {}'.format(args.square, args.square**2))
else:
print('...here')
demo5
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')
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))
可以看出,-q和-v不出现,或仅出现一个都可以,同时出现就会报错。