今天用到了一個命令行解析庫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
解析出來的是一個由元組構(gòu)成的列表,每一個元祖由opt名
和opt值
構(gòu)成
-
args
是追加到opt
后面的 參數(shù),比如第一個例子a1
,a2
-
args
不能寫在opt
之前,否則解析可能不是你想要的結(jié)果 比如:
python jf.py a1 a2 -v -h -f3333
image.png
正確的結(jié)果:
image.png