轻松编写命令行接口,argparse模块你值得拥有( 二 )


定义Boolean参数
from distutils.util import strtobool parser.add_argument(''--isFullTime'', default=True, type=strtobool, help=''Is thisEmployee Full Time? (default: %(default)s)'') FULLTIME= args.isFullTime ifFULLTIME: print(NAME+'' is a full time employee.'') else: print(NAME+'' is not a full time employee.'')
将以上代码加入到之前的脚本中 。 定义一个可选参数default=True , 这样即便不给该参数输入任何内容 , 其值默认为True 。
type=strtobool确保输入内容转变成boolean数据类型 。 否则 , 当该脚本在输入中传递时 , 它将是字符串数据类型 。 如果需要整数参数 , 也可以将其定义为type=int 。

轻松编写命令行接口,argparse模块你值得拥有
本文插图

图源:unsplash
help中的%(default)s)用来检索参数中的默认值 。 这是为了确保description不是硬编码 , 能随着默认值灵活更改 。
· 再输入name,title和address
$ python employee.py AlexManager --address ''123 Baker Street'' Name : Alex Job Title : Manager Address : 123 Baker Street Alex is a full time employee.
默认情况下isFullTime为True , 因此如果不给isFullTime输入任何参数 , 则输出结果为Alex是全职员工(Alex is a full time employee) 。
· 将默认值改为 False
$ python employee.py AlexManager --address ''123 Baker Street'' --isFullTime False Name : Alex Job Title : Manager Address : 123 Baker Street Alex is not a full time employee.
输出结果变成Alex , 不是全职员工了 。
定义输入参数范围
parser.add_argument(''--country'',choices=[''Singapore'', ''UnitedStates'', ''Malaysia''], help=''Country/Regionof Employee'') COUNTRY= args.country print(''Country :''+str(COUNTRY))
可以用choices参数限制可能输入参数的值 , 这对于防止用户输入无效值很有用 。 例如 , 通过choices=[“Singapore”, “UnitedStates”, “Malaysia”]将输入国家/地区的值限制在新加坡 , 美国和马来西亚当中 。
· 可以试试如果输入的国家名字不在choices中会发生什么
$ python employee.py AlexManager --country Japan usage: employee.py [-h] [--address ADDRESS] [--country{Singapore,United States,Malaysia}] [--isFullTimeISFULLTIME] name title employee.py: error: argument --country: invalid choice: 'Japan' (choose from'Singapore', 'United States', 'Malaysia')
用户会收到invalid choice错误警告 。 调用 --help可以获取choices的使用说明信息 。
就是这么简单 , 如何使用自定义参数创建自己的Python命令行 , 现在你已经学会啦 。

轻松编写命令行接口,argparse模块你值得拥有
本文插图

留言点赞关注
我们一起分享AI学习与发展的干货
如转载 , 请后台留言 , 遵守转载规范


推荐阅读