全文共1699字,预计学习时长11分钟
图源:unsplash
相信大多数人都会用这行命令运行python脚本。
$ python main.py
我们能否对该脚本稍作修改比如说定义自己的参数?当然可以!
$ python main.py arg1 arg2
Python中的argparse模块能解决这个问题。argparse 模块可以让人轻松编写用户友好的命令行接口。
程序定义它需要的参数,然后argparse将弄清如何从sys.argv解析出那些参数。argparse模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。
和往常一样,要做的第一件事就是安装这个Python模块。
conda install argparse
import argparse
if __name__ =="__main__":
parser = argparse.ArgumentParser(description="""
This script is going to create an employeeprofile.
""")
parser.add_argument("name", help="Name ofEmployee")
parser.add_argument("title", help="Job Titleof Employee")
parser.add_argument("--address", help="Address ofEmployee")
args = parser.parse_args()
NAME= args.name
TITLE= args.title
ADDRESS= args.address
print("Name :"+NAME)
print("Job Title : "+TITLE)
print("Address : "+ADDRESS)
创建一个ArgumentParse的对象parser,在ArgumentParser中对该脚本做简要描述。用add_argument函数定义位置和可选参数,help用来简单描述这个参数的作用。
位置参数是必须放在合适位置或是遵循一定顺序的参数。
图源:unsplash
可选参数是输入一个关键字和等号的关键字参数,输入内容是可选的。
· 尝试用help参数-h运行该脚本
$ python employee.py -h
usage: employee.py [-h] [--address ADDRESS] name titleThis script is going tocreate an employee profile.positional arguments:
name Name of Employee
title Job Title of Employeeoptionalarguments:
-h, --help show this help message and exit
--address ADDRESS Address of Employee
-h和 --help 是argparse中默认定义的参数,显示在脚本中定义的描述,为用户在使用该脚本时提供帮助。
· 输入name 和 title
$ python employee.py AlexManager
Name : Alex
Job Title : Manager
Address : None
由于address参数定义为空,在脚本中会把NoneType的值传递给它。在输出结果之前需要将其转换成字符串。
· 试试只输入name
$ python employee.py Alex
usage: employee.py [-h] [--address ADDRESS] name title
employee.py: error: the following arguments are required: title
因为title也是位置参数,所以在脚本中不可省略。
· 这次输入name,title和address。
$ python employee.py AlexManager --address 123 Baker Street
usage: employee.py [-h] [--address ADDRESS] name title
employee.py: error: unrecognized arguments: Baker Street
因为123 Baker Street中间有空格,该脚本会把Baker Street当作其他参数,这里需要使用双引号。
$ python employee.py AlexManager --address "123 Baker Street"
Name : Alex
Job Title : Manager
Address : 123 Baker Street
如果name和title包含多个单词,则要使用双引号。
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。
图源: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命令行,现在你已经学会啦。
我们一起分享AI学习与发展的干货
欢迎关注全平台AI垂类自媒体 “读芯术”
(添加小编微信:dxsxbb,加入读者圈,一起讨论最新鲜的人工智能科技哦~)