如何在执行时打印Python文件的docstring?

thi*_*ias 69 python docstring

我有一个带有docstring的Python脚本.当解析命令行参数不成功时,我想打印文档字符串以获取用户的信息.

有没有办法做到这一点?

最小的例子

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

This describes the script.
"""

import sys


if len(sys.argv) < 2:
    print("<here comes the docstring>")
Run Code Online (Sandbox Code Playgroud)

Pet*_*rin 78

docstring存储在模块的__doc__全局中.

print(__doc__)
Run Code Online (Sandbox Code Playgroud)

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

  • 这确实有效,但还有另一种方式可以在您导入该模块后显示更原生的模块帮助界面:: `help(module_name)`。 (2认同)
  • @danbgray 我认为你得到的是 argparse 的用途 (2认同)

win*_*fer 13

这是一个不硬编码脚本文件名的替代方法,而是使用sys.argv [0]来打印它.使用%(scriptName)而不是%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)
Run Code Online (Sandbox Code Playgroud)


Mar*_*oma 8

参数解析应始终使用进行argparse

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

#!/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)
Run Code Online (Sandbox Code Playgroud)

如果调用此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
Run Code Online (Sandbox Code Playgroud)