docopt creates beautiful command-line interfaces

What’s docopt

根据说明文档解析命令行参数 (generate option parser based on the beautiful help message)

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"""Naval Fate.
Usage:
naval_fate.py ship new <name>...
naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
naval_fate.py ship shoot <x> <y>
naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate.py (-h | --help)
naval_fate.py --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='Naval Fate 2.0')
print(arguments)

API

1
2
3
from docopt import docopt
docopt(doc, argv=None, help=True, version=None, options_first=False)

返回值是由选项,参数或命令作为键值的字典。(The return value is a simple dictionary with options, arguments and commands as keys, spelled exactly like in your help message)

1
2
3
4
5
6
7
8
9
10
naval_fate.py ship Guardian move 100 150 --speed=15
{'--drifting': False, 'mine': False,
'--help': False, 'move': True,
'--moored': False, 'new': False,
'--speed': '15', 'remove': False,
'--version': False, 'set': False,
'<name>': ['Guardian'], 'ship': True,
'<x>': '100', 'shoot': False,
'<y>': '150'}

帮助文档格式

帮助文档由用法 (Usage) 和选项 (Options) 两部分组成。

用法格式

用法是脚本文档的一部分,以 usage 开始 (大小写不敏感),以空行结束。

组成元素包括:

  • < arguments > ,参数用大写或用尖括号括起表示。
  • -options,选项以连接号 (-)起始的字符表示,单字母的选项可以共用一个连接符,例如:-vof 等同于 -v -o -f。选项后可以添加参数,–input=FILE , -i FILE 或者 -iFILE。
  • commands

格式:

  • “[]” 代表可选元素
  • “( )” 代表必须元素,任何不放在”[]”中的,也是必须元素
  • “|” 代表互斥元素
  • “…” 代表一个或更多元素
  • “[–]” ,使用 “- -“ 分隔位置参数,启用此功能需要在 usage 中添加 “[- -]”
  • “[-]”,代表使用标准输入作为脚本输入,启用此功能在 usage 中添加 “[-]”
选项格式

选项说明位于用法说明下方,在以下情况,选项说明是必要的:

  • 选项有长,短两种写法
  • 选项有参数
  • 选项有默认值

选项写作规则如下:

  • 以 - 或 - - 作为起始(不包括空格)
  • 使用空格或等号添加选项的参数,参数用大学字母或用尖角符括起表示,可以使用逗号分隔选项,eg:

    1
    2
    -o FILE --output=FILE # without comma, with "=" sign
    -i <file>, --input <file> # with comma, without "=" sing
  • 使用两个及以上的空格分隔选项和选项说明

  • 设置默认值的格式为:”[default: < my-default-value>]”,eg:

    1
    2
    3
    --coefficient=K The K coefficient [default: 2.95]
    --output=FILE Output file [default: test.txt]
    --directory=DIR Some directory [default: ./]
  • 如果选项不可重复,默认值被认为是字符串,否则会将默认值以空格拆分为列表。