这个例子很简单,但是对我来说够用,日后可以基于这个例子拓展
docopt: 0.6.2
python: 3.6
pip install docopt==0.6.2
(1) 注意要写在import 前面, 否则报错。
(2) 注意doc前不要添加其他三引号的内容(前面的注释可以用“#”),否则无法识别,报如下错误:
Traceback (most recent call last):
File "xxxx.py", line 26, in <module>
args = docopt(__doc__)
File "C:\Users\xxxx\anaconda3\envs\xxxx\lib\site-packages\docopt.py", line 558, in docopt
DocoptExit.usage = printable_usage(doc)
File "C:\Users\xxxx\anaconda3\envs\xxxxx\lib\site-packages\docopt.py", line 468, in printable_usage
raise DocoptLanguageError('"usage:" (case-insensitive) not found.')
docopt.DocoptLanguageError: "usage:" (case-insensitive) not found.
"""
Usage:
vocab.py [options] TRAIN_SET_SRC TRAIN_SET_TGT VOCAB_FILE
Options:
-h --help Show this screen.
--size-src INT src vocab size [default: 50000]
--size-tgt INT tgt vocab size [default: 50000]
--freq-cutoff INT frequency cutoff [default: 2]
--vocab-class STR the class name of used Vocab class [default: Vocab]
"""
from docopt import docopt
if __name__ == "__main__":
args = docopt(__doc__)
print(args)
必选参数:
TRAIN_SET_SRC TRAIN_SET_TGT VOCAB_FILE
可选参数:
-h --help Show this screen.
–size-src INT src vocab size [default: 50000]
–size-tgt INT tgt vocab size [default: 50000]
–freq-cutoff INT frequency cutoff [default: 2]
–vocab-class STR the class name of used Vocab class [default: Vocab]
执行方法:
python ../vocab.py --size-src 10000 ../samples/train/train.spl.src ../samples/train/train.txt.tgt ../samples/dic/python_dic.json
*该命令制定了可选参数(–size-src)的值以及必选参数的值
结果:
{'--freq-cutoff': '2',
'--help': False,
'--size-src': '10000',
'--size-tgt': '50000',
'--vocab-class': 'Vocab',
'TRAIN_SET_SRC': '../samples/train/train.spl.src',
'TRAIN_SET_TGT': '../samples/train/train.txt.tgt',
'VOCAB_FILE': '../samples/dic/python_dic.json'}