显示带docopt但不带-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__

另一个与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时,您将获得完整的帮助屏幕。

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

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

让我们看看还有什么…

相关内容

  • 没有找到相关文章