当执行Python文件时,我如何打印出它的文档字符串?

98

我有一个带有文档字符串的Python脚本。当命令行参数解析失败时,我想打印文档字符串以便用户了解。

是否有任何方法可以实现这一点?

最小示例

#!/usr/bin/env python
"""
Usage: script.py

This describes the script.
"""

import sys


if len(sys.argv) < 2:
    print("<here comes the docstring>")

2
有用于命令行参数解析的库:argparse(>=2.7)和optparse。http://docs.python.org/dev/library/argparse.html http://docs.python.org/dev/library/optparse.html - codeape
12
我明白了,但这和问题无关。 - thias
1
我是一个人,有时明确地不想为一个非常简单的脚本使用argparse,因此我很感激下面那些按照要求回答问题的人。 - SteveWithamDuplicate
5个回答

118

文档字符串存储在模块的 __doc__ 全局变量中。

print(__doc__)

顺便说一下,对于任何模块都是适用的:import sys; print(sys.__doc__)。函数和类的文档字符串也在它们的__doc__属性中。


2
那肯定可以运行,但还有另一种方式可以展示更本地化的模块帮助界面:在导入该模块后使用 help(module_name) - danbgray
2
@danbgray 我想你在说argparse的用途是什么。 - james-see
1
奇怪的Python 2皱纹:如果您在文档字符串之前放置“from __future__ import print_function”等内容,则它不再是文档字符串。但是,您可以在文档字符串之后仅放置“from __future__”import ...,并且仍满足“from __future__ imports必须出现在文件开头”的规则。 - SteveWithamDuplicate

17

应该总是使用argparse进行参数解析。

您可以通过将其传递给Argparse的description参数来显示__doc__字符串:

#!/usr/bin/env python
"""
This describes the script.
"""


if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser(description=__doc__)
    # Add your arguments here
    parser.add_argument("-f", "--file", dest="myFilenameVariable",
                        required=True,
                        help="write report to FILE", metavar="FILE")
    args = parser.parse_args()
    print(args.myFilenameVariable)

如果您将此文件命名为mysuperscript.py并执行它,您会得到:

$ ./mysuperscript.py --help
usage: mysuperscript.py [-h] -f FILE

This describes the script.

optional arguments:
  -h, --help            show this help message and exit
  -f FILE, --file FILE  write report to FILE

14

这里有一种替代方案,不是硬编码脚本文件名,而是使用sys.argv[0]打印它。使用%(scriptName)s而不是%s可以提高代码的可读性。

#!/usr/bin/env python
"""
Usage: %(scriptName)s

This describes the script.
"""

import sys
if len(sys.argv) < 2:
   print __doc__ % {'scriptName' : sys.argv[0].split("/")[-1]}
   sys.exit(0)

通常我会有一个使用()函数,它使用sys.argv[0],在打印docstring之前调用。谢谢。 - thias
@wint3rschlaefer,你能解释一下Usage: %(scriptName)s是如何获取脚本名称的吗?在Python中这种机制叫什么? - olala
1
@wint3rschlaefer 或许值得更新为 Python3 版本,例如 """使用方法:{scriptName}""".format(scriptName = sys.argv[0]) - Cimbali
1
使用 name 怎么样? - Otzen

1
这将在--help是唯一的参数时打印__doc__字符串
if __name__=='__main__':
 if len(sys.argv)==2 and sys.argv[1]=='--help':
    print(__doc__)

适用于以下两种方式:

  • ./yourscriptname.py --help
  • python3 yourscriptname.py --help

1

这是@MartinThoma答案的增强版,它可以打印多行docstring,灵感来自于Python argparse:如何在帮助文本中插入换行符?

Argument parsing should always be done with argparse.

You can display the doc string by passing it to the description parameter of Argparse:

#!/usr/bin/env python 
""" 
This summarizes the script.

Additional descriptive paragraph(s).
"""  # Edited this docstring


if __name__ == '__main__':
    from argparse import ArgumentParser, RawTextHelpFormatter  # Edited this line
    parser = ArgumentParser(description=__doc__
                            formatter_class=RawTextHelpFormatter)  # Added this line
    # Add your arguments here
    parser.add_argument("-f", "--file", dest="myFilenameVariable",
                        required=True,
                        help="write report to FILE", metavar="FILE")
    args = parser.parse_args()
    print(args.myFilenameVariable) 

If you call this mysuperscript.py and execute it you get:

$ ./mysuperscript.py --help
usage: mysuperscript.py [-h] -f FILE

This summarizes the script.

Additional descriptive paragraph(s).

optional arguments:
  -h, --help            show this help message and exit
  -f FILE, --file FILE  write report to FILE
没有添加formatter_class,文档字符串中就不会有换行符。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接