|
- # coding:utf-8
- import math
- import sys
- import argparse
- import os.path as osp
-
-
- # 1、计算体积基础代码
-
- # def cylinder_volume(radius,height):
- # volume = (math.pi) * (radius ** 2) * height
- # return volume
-
- # if __name__ == '__main__':
- # vol = cylinder_volume(4,2)
- # print(vol)
-
- # # 2、使用argparse模块进行代码导入
- # # 2.1 创建对象
- # parser = argparse.ArgumentParser(description='Calculate volume of a cylinder')
- # # 2.2 添加参数
- # parser.add_argument('radius',type=int, help='Radius of a Cylinder')
- # parser.add_argument('height',type=int, help='Height of a Cylinder')
- # # 2.3 解析参数
- # args = parser.parse_args()
- #
- # def cylinder_volume(radius,height):
- # volume = (math.pi) * (radius ** 2) * height
- # return volume
- #
- # if __name__ == '__main__':
- # # 替换实参
- # vol = cylinder_volume(args.radius,args.height)
- # print(vol)
-
- # 3。增加长符号,参数位置可选。否则参数位置必须按照顺序
- #
- parser = argparse.ArgumentParser(description='Calculate volume of a cylinder')
- # 添加required提示,缺少参数时,报错提示
- parser.add_argument('-r','--radius',type=int, required=True,help='Radius of a Cylinder')
- parser.add_argument('-H','--height',type=int, help='Height of a Cylinder')
-
- # 添加互斥组(互斥事件,互斥锁)
- group = parser.add_mutually_exclusive_group()
- # action='store_true',默认值为False,当执行这个命令时,会激活为True
- group.add_argument('-q','--quiet',action='store_true',help='print quiet')
- group.add_argument('-v','--verbose',action='store_true',help='print quiet')
- parser.add_argument('-s', '--storefile', type=str, default=None)
-
- args = parser.parse_args()
-
- def cylinder_volume(radius,height,savefile):
- volume = (math.pi) * (radius ** 2) * height
- with open(savefile + '.pth','w') as f:
- f.write(str(volume))
- return volume
-
- if __name__ == '__main__':
- # 替换实参
- vol = cylinder_volume(args.radius,args.height,args.storefile)
- if args.quiet:
- print(vol)
- elif args.verbose:
- print('volume of Cylinder with radius %s and height %s',args.radius,args.height)
-
- else:
- print('valume of Cyliner = %s',vol)
-
-
|