介绍
"""
用法
样例
docopt的使用非常简单,以Qingchat为例,你只需要在代码最开头加入:
"""Qingchat CLI
Usage:
qingchat config ip <ip>
qingchat config port <port>
qingchat config login
qingchat group list
qingchat group choose <group_name>...
qingchat group clean
qingchat group send -t <content>
qingchat group send -i <media>
qingchat group send -f <file> [<delaytime>]
Options:
-h --help Show this screen.
-v --version Show version.
"""
然后在执行代码中加入:
arguments = docopt(__doc__, version='Qingchat 0.3.2')
arguments
{
'-f': False,
'-i': False,
'-t': False,
'<content>': None,
'<file>': None,
'<group_name>': [],
'<ip>': '127.0.0.1',
'<media>': None,
'<port>': None,
'choose': False,
'clean': False,
'config': True,
'group': False,
'ip': True,
'list': False,
'login': False,
'port': False,
'send': False
}
arguments['xxx']
详解
docopt
Usage
usage:
(区分大小写)和一个空行之间的文本都会被识别为一个命令组合, usage
参数
<argument>
或者 ARGUMENT
True
或者 False
Usage: my_program <host> <port>
选项
-o
或者 --option
True
或者 False
Usage: my_program -f <file>
Tips:
- 短选项可以组合起来,比如
-abc
- 等价于
-a -b -c
- 长选项需要的参数需要使用
=
- 或者空格来分隔,
--input=ARG
- 等价于
--input ARG
- 短选项可以不需要空格,
-f FILE
- 等价于
-fFILE
命令
--options
或者 <arguments>
True
或者 False
可选项
[optional elements]
elements
在相同或者不同的括号中都是一样的:
Usage: my_program [command --option <argument>]
等价于
Usage: my_program [command] [--option] [<argument>]
必填项
(required elements)
()
Usage: my_program (--either-this <and-that> | <or-this>)
选择项
element|another
Usage: my_program go (--up | --down | --left | --right)
列表项
element...
比如说:
Usage: my_program open <file>...
arguments['<file>']
Option
Option
- 将某个短参数与长参数关联起来,比如
-i <file>, --input <file>
- 某个选项有一个参数
- 选项的默认值,比如
--coefficient=K The K coefficient [default: 2.95]