今天用到了一个命令行解析库getopt
, 用起来和docopt
差不多,但是注意使用方式,查看文档可以了解一些getopt 文档地址。
>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
还有一个长格式:
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
... 'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']
这个解析方式如下:
1.opts
解析出来的是一个由元组构成的列表,每一个元祖由opt名
和opt值
构成
-
args
是追加到opt
后面的 参数,比如第一个例子a1
,a2
-
args
不能写在opt
之前,否则解析可能不是你想要的结果 比如:
python jf.py a1 a2 -v -h -f3333
image.png
正确的结果:
image.png