docopt根据你写的文档描述,可以自动为你生成解析器,可以非常容易的为你的python程序创建命令行界面(Command Line Interface,CLI)。
docopt的视频介绍链接:PyCon UK 2012: Create *beautiful* command-line interfaces with Python
一个简单的例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
"""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
)
|
安装
docopt在Python 2.5, 2.6, 2.7, 3.2, 3.3和PyPy环境下测试过。使用pip或者easy_install:
1
|
pip
install
docopt
==
0.6.1
|
API
1
|
docopt
(
doc
,
argv
=
None
,
help
=
True
,
version
=
None
,
options_first
=
False
)
|
doc可以是一个文档字符串,比如:
1
2
3
4
5
6
|
"""Usage: my_program.py [-hso FILE] [--quiet | --verbose] [INPUT ...]-h --help show this
-s --sorted sorted output
-o FILE specify output file [default: ./test.txt]
--quiet print less text
--verbose print more text
"""
|
argv默认使用sys.argv[1:],如果运行以下命令:
1
|
naval_fate
.
py
ship
Guardian
move
100
150
--
speed
=
15
|
则返回一个字典,形如:
1
2
3
4
5
6
7
8
|
{
'--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'
}
|
帮助消息格式
帮助消息由两部分组成,
1. Usage pattern形如:
1
|
Usage
:
my_program
.
py
[
-
hso
FILE
]
[
--
quiet
|
--
verbose
]
[
INPUT
.
.
.
]
|
2. Option descriptions形如:
1
2
3
4
5
|
-
h
--
help
show
this
-
s
--
sorted
sorted
output
-
o
FILE
specify
output
file
[
default
:
.
/
test
.
txt
]
--
quiet
print
less
text
--
verbose
print
more
text
|
更多Demo
docopt官方提供了很多样例以供学习参考:https://github.com/docopt/docopt/tree/master/examplesdocopt与其他语言
存在以下编程语言的docopt:
- Ruby port
- CoffeeScript port
- Lua port
- PHP port