gpt4 book ai didi

python - 使用 Python 的 optparse 模块时如何遵守 PEP 257 文档字符串?

转载 作者:太空狗 更新时间:2023-10-30 00:37:34 24 4
gpt4 key购买 nike

根据 PEP 257命令行脚本的文档字符串应该是它的用法信息。

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

所以我的文档字符串看起来像这样:

<tool name> <copyright info>Usage: <prog name> [options] [args]some text explaining the usage...Options:  -h, --help  show this help message and exit   ...

Now I want to use the optparse module. optparse generates the "Options" sections and a "usage" explaining the command line syntax:

from optparse import OptionParser

if __name__ == "__main__":
parser = OptionParser()
(options, args) = parser.parse_args()

因此使用“-h”标志调用脚本打印:

Usage: script.py [options]Options:    -h, --help  show this help message and exit

This can be modified as follows:

parser = OptionParser(usage="Usage: %prog [options] [args]",
description="some text explaining the usage...")

结果

Usage: script.py [options] [args]some text explaining the usage...Options:  -h, --help  show this help message and exit

但是我怎样才能在这里使用文档字符串呢?将文档字符串作为用法消息传递有两个问题。

  1. 如果文档字符串不是以“Usage:”开头,optparse 会将“Usage:”附加到文档字符串
  2. 文档字符串中必须使用占位符 '%prog'

结果

根据答案,似乎没有办法重用 optparse 模块预期的文档字符串。所以剩下的选择是手动解析文档字符串并构造 OptionParser。 (所以我会接受 S.Loot 的回答)

“用法:”部分由 IndentedHelpFormatter 引入,可以用 OptionParser.__init__() 中的格式化参数替换。

最佳答案

我写了一个模块 docopt 来做你想做的事——在 docstring 中写 usage-message 并保持 DRY。它还允许完全避免编写乏味的 OptionParser 代码,因为 docopt 正在生成解析器基于使用消息。

查看:http://github.com/docopt/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)

关于python - 使用 Python 的 optparse 模块时如何遵守 PEP 257 文档字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1259982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com