使用 docopt 不带 -h 显示完整的文档字符串

Display the complete docstring with docopt without -h

我正在尝试使用 docopt 显示所有帮助消息,而不添加 --help 参数。

例如这是来自官方文档:

"""
Naval Fate.

Usage:
  naval_fate ship new <name>...
  naval_fate ship <name> move <x> <y> [--speed=<kn>]
  naval_fate ship shoot <x> <y>
  naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate -h | --help
  naval_fate --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
arguments = docopt(__doc__, version=1)

如果我不带参数调用脚本,docopt 显示用法部分:

$ python foo.py 
Usage:
  naval_fate ship new <name>...
  naval_fate ship <name> move <x> <y> [--speed=<kn>]
  naval_fate ship shoot <x> <y>
  naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate -h | --help
  naval_fate --version

而且我必须显式设置 --help 参数才能查看完整帮助:

$ python foo.py --help
Naval Fate.

Usage:
  naval_fate ship new <name>...
  naval_fate ship <name> move <x> <y> [--speed=<kn>]
  naval_fate ship shoot <x> <y>
  naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate -h | --help
  naval_fate --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine. 

赶上 DocoptExit 应该可以。像这样:

"""
Naval Fate.

Usage:
  naval_fate ship new <name>...
  naval_fate ship <name> move <x> <y> [--speed=<kn>]
  naval_fate ship shoot <x> <y>
  naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate -h | --help
  naval_fate --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, DocoptExit
try:
    arguments = docopt(__doc__, version=1)
except DocoptExit:
    print __doc__

我总是挠头想知道为什么这不是默认行为,最后针对这个问题打开了一个错误:

https://github.com/docopt/docopt/issues/410

让我们看看追加了什么...

与 J. P. Petersen 的回答中显示的选项一样有效的另一个选项是:

import sys

# ...

if len(sys.argv) == 1: # i.e just the program name
    sys.argv.append('-h')

arguments = docopt(__doc__, version=1)

现在,当您 运行 python foo.py 时,您会看到完整的帮助屏幕。