好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

使用Python中的命令行参数解析工具之docopt详细介绍

docopt 是一个用来解析命令行参数的工具,当想要在 Python 程序后面附加参数时,就不需要再为此而发愁了。下面这篇文章主要介绍了Python中命令行参数解析工具之docopt的相关资料,介绍的非常详细,需要的朋友们下面来一起看看吧。

"""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) 
-o FILE --output-FILE  # 不使用逗号,使用 = 符号
-i <file>, --input <file> # 使用逗号,不使用 = 符号 
--coefficient=K The K coefficient [default: 2.95]
--output=FILE Output file [default: test.txt]
--directory=DIR Some directory [default: ./] 
{'--drifting': False,
 '--help': False,
 '--moored': False,
 '--speed': '15',
 '--version': False,
 '<name>': ['Guardian'],
 '<x>': '100',
 '<y>': '150',
 'mine': False,
 'move': True,
 'new': False,
 'remove': False,
 'set': False,
 'ship': True,
 'shoot': False} 

从打印信息可以看到,对于选项,使用布尔型来表示用户是否输入了该选项,对于参数,则使用具体值来表述。

这样一来,程序就可以从arguments变量中得到下一步的操作了。若是用户什么参数都没输入,则打印Usage说明提示输入内容。

以上就是使用Python中的命令行参数解析工具之docopt详细介绍的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于使用Python中的命令行参数解析工具之docopt详细介绍的详细内容...

  阅读:47次