4

我正在尝试使用 显示所有帮助消息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. 
4

3 回答 3

3

抓住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__
于 2015-07-17T15:32:03.700 回答
0

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

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

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

于 2018-03-21T22:32:25.043 回答
0

另一个与 JP 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,您会看到完整的帮助屏幕。

于 2018-08-14T20:53:54.300 回答