OptionParser的意义
用来接收用户在命令行敲入的参数,并解析这些参数。下面用一段简单的代码举个例子:
from optparse import OptionParser
import sys
op = OptionParser()
op.add_option('-p', action='store_true', dest='print', help='如果为真,打印积极的语句;如果为假,打印消极的语句')
op.print_help()
opts, args = op.parse_args(sys.argv[1:])
if opts.print:
print('我很开心')
else:
print('我很难过')
下图是在命令行(Anaconda Prompt)中实际运行的效果:
上面的例子是观察命令行传入的参数是否有-p参数。如果有,程序就输出“我很开心”, 否则输出“我很难过”。
在此给出一个实际应用的例子:
https://scikit-learn.org/stable/auto_examples/text/plot_document_classification_20newsgroups.html
比如其中一行代码如下:
op.add_option("--chi2_select", action="store", type="int", dest="select_chi2", help="Select some number of features using a chi-squared test")
这一行代码是针对特征选择。根据命令行传入的参数判断是否应用卡方检验筛选特征,并且知道用卡方检验筛选出几个特征。
OptionParser的使用
一、导入包:from optparse import OptionParser
二、创建对象:op = OptionParser()
三、在这个对象中添加自定义的命令参数:op.add_option(...)
add_option常用的几个参数:
1. 第一个或第二个参数一般是自定义的参数在命令行中的名称。比如自定义一个命令行参数为' -f '(简称)、' --file '(全称),在命令行中敲入' -f '或' --file '就能识别出自定义的命令。
op.add_option('-f', '--file', action='store', type='string', dest='filename', help='Input filename')
2. action='store' / 'store_true' / 'store_false'
①store:将用户在命令行输入的值存入变量中。
比如用户在命令行输入 -f hello.txt,那么程序就会得到键值对{'filename' : 'hello.txt'};如果用户只输入 -f ,没有给值,且add_option没有设置default属性,那么filename值为空,即{'filename' : None}
②store_true:如果出现指定的命令参数,则对应键值对为True。
op.add_option('-p', action='store_true', dest='print', help='如果为真,打印积极的语句;如果为假,打印消极的语句')
比如上面这段代码,在命令行输入-p,会得到键值对{'print' : True}
③store_false:与store_true类似,如果出现指定的命令参数,则对应键值对为False。
3. type:指定值的数据类型
4. dest:键值对的键名
5. help:提示用户的帮助信息。可以使用op.print_help()打印OptionParser中所有的帮助信息。
四、解析命令行传入的参数(两种方式)
# 解析命令行传入的参数
# 从第1个参数进行解析,因为第0个参数是文件的路径
opts, args = op.parse_args(sys.argv[1:])
# 解析给定的列表
fakeArgs = ['-f', 'file.txt', '-p', 'arg1', 'arg2']
opts, args = op.parse_args(fakeArgs)
# opts -> {'filename':'file.txt', 'print':True}
# args -> ['arg1', 'arg2']
解析后返回的opts是字典,args是列表。上文中频频提到的键值对指的就是opts。
满足自定义的键值对会被放在opts中,剩下的会放在args中。