1.2. argparse
argparse是python自带的命令行参数解析模块,可以用来解析命令行参数。
1.2.1. 入门
# 我们写一个脚本,传递长 和宽 ,我们计算出来面积数据。 支持以debug运行,展示计算过程。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--width', type=int)
parser.add_argument('--height', type=int)
parser.add_argument('--debug', action='store_true')
# 解析终端参数
args = parser.parse_args()
# 打印下参数
#print(dict(args))
# 计算面积
def area(width, height):
return width * height
area_result = area(args.width, args.height)
if args.debug:
print(f'debug: width:{args.width}, height:{args.height}')
print(f'area_result:{area_result}')
# python3 08.argparse_demo01.py --width=10 --height=20 --debug
# debug: width:10, height:20
# area_result:200
1.2.2. 分组形式
import argparse
import math
def calculate_rectangle_area(length, width):
return length * width
def calculate_circle_area(radius):
return math.pi * (radius ** 2)
def main():
parser = argparse.ArgumentParser(description="计算长方形或圆形的面积")
# 添加选择形状的参数
parser.add_argument('shape', type=str, choices=['rectangle', 'circle'], help='选择计算的形状')
# 创建参数组
rectangle_group = parser.add_argument_group('长方形参数')
rectangle_group.add_argument('--height', type=float, help='长方形的长度')
rectangle_group.add_argument('--width', type=float, help='长方形的宽度')
circle_group = parser.add_argument_group('圆形参数')
circle_group.add_argument('--radius', type=float, help='圆形的半径')
args = parser.parse_args()
# 根据选择的形状解析参数
if args.shape == 'rectangle':
if args.height is None or args.width is None:
parser.error("对于长方形,必须提供长度和宽度")
area = calculate_rectangle_area(args.height, args.width)
shape = "长方形"
elif args.shape == 'circle':
if args.radius is None:
parser.error("对于圆形,必须提供半径")
area = calculate_circle_area(args.radius)
shape = "圆形"
print(f"The area of the {shape} is: {area:.2f}")
if __name__ == "__main__":
main()
# python3 08.argparse_demo02.py rectangle --width=10 --height=20
# The area of the 长方形 is: 200.00
# python3 08.argparse_demo02.py circle --radius=10
# The area of the 圆形 is: 314.16