【转自官网】基本用法熟悉一波
Argparse 教程:https://docs.python.org/zh-cn/3/howto/argparse.html
https://docs.python.org/zh-cn/3/library/argparse.html?highlight=argparse#module-argparse
注意下 action 与 default 的区别:default 是参数啥都没有,那就默认的这个参数,action是如果参数符合,则使用action中的值
同时注意下 dest 的用法:
# @TIME : 2019/11/9 下午6:04
# @File : just.py
# 位置参数介绍
# import argparse
# parser = argparse.ArgumentParser()
# # parser.add_argument('echo', help="echo the string you use here")
# parser.add_argument("square", help="display a square of a given number", type=int)
# args = parser.parse_args()
# print(args.square**2)
# 可选参数介绍
# import argparse
# parser = argparse.ArgumentParser()
# parser = argparse.ArgumentParser()
# parser.add_argument("--verbose", help="increase output verbosity",
# action="store_true")
# args = parser.parse_args()
# if args.verbose:
# print("verbosity turned on")
# 短选项
# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument("-v", "--verbose", help="increase output verbosity",
# action="store_true")
# args = parser.parse_args()
# if args.verbose:
# print("verbosity turned on")
# 结合位置参数和可选参数
# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument("square", type=int, help='display a square of a given number')
# parser.add_argument("-v", '--verbose', action='store_true', help='increase outpu verbosity')
# args = parser.parse_args()
# answer = args.square**2
#
# if args.verbose:
# print("the square of {} equals {}".format(args.square, answer))
# else:
# print(answer)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int,
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
print("{}^2 == {}".format(args.square, answer))
else:
print(answer)