简介
python的getopt模块是一种C风格的命令行选项及参数解析,主要是协助脚本解析sys.argv中的命令行参数,如果熟悉C语言的getopt()的话,比较好理解
先从一个实例来分析
一个实例
要求:
- 有一个
-h选项,也可以使用--help来打印脚本用法 - 有一个
-v选项,也可以使用--verbose来实现详细的日志输出 - 有一个
-o选项,也可以使用--output,后面要跟一个值,表示输出信息存放的文件等
这里只实现对命令行选项的解析,不实现真实的功能,从要求来看,脚本使用可能如下
python test.py -h
python test.py --help
python test.py -v -o test.log
python test.py --verbose --output test.log
代码如下
import sys
import getopt
def usage():
print("[usage]:")
print("python test.py -h")
print("python test.py [-v] -o [logfile]")
def testGetOpt():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["verbose","help", "output="])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
output = None
verbose = False
print("opts = %s, args = %s" % (opts, args))
for o, a in opts:
if o in ("-v", "--verbose"):
verbose = True
print("get -v, set verbose = %s" % verbose)
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
print("get -o, set output = %s" % output)
else:
assert False, "UNHANDLED OPTION"
if __name__ == "__main__":
testGetOpt()
脚本执行及输出信息如下:
D:\scan\python>python testopt.py -h
opts = [('-h', '')], args = []
[usage]:
python test.py -h
python test.py [-v] -o [logfile]
D:\scan\python>python testopt.py --help
opts = [('--help', '')], args = []
[usage]:
python test.py -h
python test.py [-v] -o [logfile]
D:\scan\python>python testopt.py -v -o test.log
opts = [('-v', ''), ('-o', 'test.log')], args = []
get -v, set verbose = True
get -o, set output = test.log
D:\scan\python>python testopt.py --verbose -output test.log
opts = [('--verbose', ''), ('-o', 'utput')], args = ['test.log']
get -v, set verbose = True
get -o, set output = test.log
D:\scan\python>
使用分析
getopt模块最主要的接口就是与模块同名的接口getopt(),还有一个gnu_getopt()接口,两者的区别在下面说明
getopt.getopt(args, shortopts, longopts=[])
-
args,表示命令行参数集合,可以通过sys.argv[1:]来获取,第一个参数是脚本名称,后面就是选项以及参数值 -
shortopts,表示短选项列表,以字符串形式给出,即一个'-'后面跟一个字符的形式,如-h -
longopts,表示长选项列表,以字符串列表形式给出,即一个'--'后面跟一个单词的形式,如下--help - 选项列表中各选项没有位置顺序要求,例如上面例子中短选项也可以写成"hvo:"
- 选项说明:
- 在短选项中单个字符表示选项,在长选项中单个单词表示选项
- 在短选项中单个字符后面带一个
:表示该选项需要一个参数,例如上面的o:; 同时长选项中单词要后面跟一个=,例如上面的output=
这个接口还有一个特殊的限制:命令行参数(非选项)后面都会解析成参数,如下
D:\scan\python>python testopt.py 1 -v -o test.log
opts = [], args = ['1', '-v', '-o', 'test.log']
D:\scan\python>
命令行中1没在选项列表中,表示是一个参数,但是因为-v、-o都在参数之后,解析时被当成参数来解析了,即打印中opts为空
为了解除这个限制,引入了一个gnu_getopt()接口
getopt.gnu_getopt(args, shortopts, longopts=[])
参数与getopt.getopt()接口一致,与此接口最大的区别就是命令行中参数和选项的位置可以随意,上面的例子中改成调用getopt.gnu_getopt()之后的结果如下
D:\scan\python>python testopt.py 1 -v -o test.log
opts = [('-v', ''), ('-o', 'test.log')], args = ['1']
get -v, set verbose = True
get -o, set output = test.log
D:\scan\python>
getopt.GetoptError
当参数列表中出现不可识别的选项或者当一个需要参数的选项未带参数时将引发此异常










网友评论