docopt 的基本示例

docopt 將命令列引數解析為其頭部。你只需編寫程式的用法字串,而不是解析引數,docopt 會解析用法字串並使用它來提取命令列引數。

"""
Usage:
    script_name.py [-a] [-b] <path>

Options:
    -a            Print all the things.
    -b            Get more bees into the path.
"""
from docopt import docopt

if __name__ == "__main__":
    args = docopt(__doc__)
    import pprint; pprint.pprint(args)

樣品執行:

$ python script_name.py
Usage:
    script_name.py [-a] [-b] <path>
$ python script_name.py something
{'-a': False,
 '-b': False,
 '<path>': 'something'}
$ python script_name.py something -a
{'-a': True,
 '-b': False,
 '<path>': 'something'}
$ python script_name.py -b something -a
{'-a': True,
 '-b': True,
 '<path>': 'something'}