getopt 命令行解析

今天用到了一個命令行解析庫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值構成

  1. args 是追加到opt后面的 參數,比如第一個例子a1a2
  2. args 不能寫在opt 之前,否則解析可能不是你想要的結果 比如:
python jf.py a1 a2 -v -h -f3333
image.png

正確的結果:


image.png
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容