1 import argparse
2
3
4 def desc_a_person(profession, hobby=None, salary=None, gender=None, has_house=False, has_car=False):
5 desc_instance = f"我的职业是:{profession},"
6 if hobby:
7 desc_instance = desc_instance + f"爱好:{hobby},"
8 if salary:
9 desc_instance = desc_instance + f"月薪是:{salary},"
10 if gender:
11 desc_instance = desc_instance + f"性别是:{gender},"
12 if has_house:
13 desc_instance = desc_instance + "有房,"
14 if has_car:
15 desc_instance = desc_instance + "有车,"
16 print(desc_instance)
17
18
19 if __name__ == '__main__':
20 """
21 add_argument() 函数参数配置
22 name or flags - 指定参数的形式,想写几个写几个,不过我们一般就写两个,一个短参数,一个长参数,看下面的例子"-f", "–file"
23 nargs - 指定这个参数后面的value有多少个, # 选项值+表示至少一个,?表示一个或0个,*0个或多个
24 default - 如果命令行没有出现这个选项,那么使用default指定的默认值
25 type - 如果希望传进来的参数是指定的类型
26 choices - 设置参数值的范围
27 required - 如果required=True那么就是必须的了
28 metavar - 参数的名字,在显示 帮助信息时才用到
29 help - 设置这个选项的帮助信息
30 dest - 设置这个选项的值就是解析出来后放到哪个属性中 #parser.add_argument("-q", dest="world")
31 """
32 introduce_arg = argparse.ArgumentParser(description="introduce yourself")
33 introduce_arg.add_argument('-p', '--profession', required=True, help="input your profession", type=str)
34 introduce_arg.add_argument('-y', '--hobby', nargs='+', required=False, help='input your hobby', type=str)
35 introduce_arg.add_argument('-s', '--salary', required=False, help='input your salary', type=str)
36 introduce_arg.add_argument('-g', '--gender', required=False, help='choose your gender', choices=['woman', 'man'],
37 type=str)
38 introduce_arg.add_argument('-o', '--has_house', required=False, help='choose your house', default=False,
39 choices=[True], type=bool)
40 introduce_arg.add_argument('-r', '--has_car', required=False, help='choose your car', default=False,
41 choices=['True'], type=str)
42 args = introduce_arg.parse_args()
43 print(args)
44 desc_a_person(args.profession, hobby=args.hobby, salary=args.salary, gender=args.gender, has_house=args.has_house,
45 has_car=args.has_car)
46
47 # python main.py -p tea -y dance swiming -s 20000 -g man -o True
48 # 我的职业是:tea,爱好:['dance', 'swiming'],月薪是:20000,性别是:man,有房,
49
50 # python main.py -p tea -y dance swiming -s 20000 -g man -o True -r True
51 # 我的职业是:tea,爱好:['dance', 'swiming'],月薪是:20000,性别是:man,有房,有车,
Original: https://www.cnblogs.com/zengmuyao/p/16357734.html
Author: 奇成
Title: python命令行解析模块argparse
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/603542/
转载文章受原作者版权保护。转载请注明原作者出处!