argparse 模块可以让人轻松编写用户友好的命令行接口,该模块能将命令行中输入的参数解析出来,并执行相应的操作。
用一个空调的例子来讲子命令的创建与解析
1.一台没有任何功能的空调
#AC.py
import argparse
# create the air condition
AC = argparse.ArgumentParser(description='This is a ari condition.')
AC.add_argument('--state', default=False, help='The state of the AC.(True/False)')
args=AC.parse_args()
2.具有制冷和制热模式的空调
子命令,可以理解为空调切换模式,空调有制冷模式、制热模式,而制冷模式下可以调冷气的温度(’ --tmp’),制热模式下可以调暖气的的温度(’–tmp’)。(虽然都是调节温度,但是效果是不一样的。)
import argparse
# create the air condition
AC = argparse.ArgumentParser(description='This is a ari condition.')
AC.add_argument('--state', default=False, help='The state of the AC.(True/False)')
subparsers = AC.add_subparsers(help='sub-command help')
# create the parser for the "Refrigeration_mode" command
Refrigeration_mode = subparsers.add_parser('Refg_M', help='The mode of refrigeration.')
Refrigeration_mode.add_argument('--tmp', type=int, help='The temperature of refrigeration_mode.')
# create the parser for the "Heating_mode" command
Heating_mode = subparsers.add_parser('Heat_M', help='The mode of heating.')
Heating_mode.add_argument('--tmp',type=int, help='The temperature of heat_mode.')
args=AC.parse_args()
subparsers.add_parser()
方法添加子命令,相当于给空调添加各种模式,而add_argument()
定义单个的命令行参数应当如何解析。’–tmp’命令解析为整数型的温度。
如:
通过 python -i AC.py
打开文件并进入交互模式。
- 打开空调
(base) W:\Projects>python -i AC.py --state True
>>> args
Namespace(mode=None, state='True')
>>>
- 打开空调,将制冷温度调到24°
(base) W:\Projects>python -i AC.py --state True Refg_M --tmp 24
>>> args
Namespace(mode='Refg_M', state='True', tmp=24)
>>>
- 打开空调,将制热温度调至32°
(base) W:\Projects>python -i AC.py --state True Heat_M --tmp 32
>>> args
Namespace(mode='Heat_M', state='True', tmp=32)
>>>