【问题标题】:How can I print a Python file's docstring when executing it?执行时如何打印 Python 文件的文档字符串?
【发布时间】:2011-10-17 09:09:03
【问题描述】:

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

有什么办法吗?

小例子

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

This describes the script.
"""

import sys


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

【问题讨论】:

标签: python docstring


【解决方案1】:

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

print(__doc__)

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

【讨论】:

  • 这绝对有效,但还有另一种方法可以在您导入该模块后显示更原生的模块帮助界面:: help(module_name)
  • @danbgray 我认为你得到的是 argparse 的用途
  • WEIRD PYTHON 2 WRINKLE:如果你输入,例如"from __future__ import print_function" 在文档字符串之前,它不再是文档字符串了。但是你可以把 "from __future__" import...放在 docstring 之后,仍然满足“from __future__ 导入必须在文件开头”的规则。
【解决方案2】:

应始终使用argparse 完成参数解析。

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

#!/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

【讨论】:

    【解决方案3】:

    这里有一个替代方案,它不对脚本的文件名进行硬编码,而是使用 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] 的 usage() 函数,它在打印文档字符串之前被调用。
    • @wint3rschlaefer,您能解释一下 Usage: %(scriptName)s 如何获取脚本名称吗?这个机制在python中叫什么?
    • @wint3rschlaefer 也许值得用python3版本更新,比如"""Usage: {scriptName}""".format(scriptName = sys.argv[0])
    • 使用 _name 怎么样?
    【解决方案4】:

    --help 是唯一参数时,这将打印__doc__ 字符串

    if __name__=='__main__':
     if len(sys.argv)==2 and sys.argv[1]=='--help':
        print(__doc__)
    

    两者都适用:

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

    【讨论】:

      【解决方案5】:

      @MartinThoma 的答案的增强,因此它可以打印受Python argparse: How to insert newline in the help text? 启发的多行文档字符串。

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

      您可以通过将 doc 字符串传递给描述来显示它 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) 
      

      如果你调用这个 mysuperscript.py 并执行它,你会得到:

      $ ./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,输出将不会在文档字符串中包含换行符。

      【讨论】:

        猜你喜欢
        • 2018-03-16
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        • 2020-05-09
        相关资源
        最近更新 更多