【问题标题】:Python Get Docstring Without Going into Interactive ModePython 在不进入交互模式的情况下获取文档字符串
【发布时间】:2010-11-19 05:29:04
【问题描述】:

我想在我的命令行应用程序中获取文档字符串,但是每次我调用内置的 help() 函数时,Python 都会进入交互模式。

如何获取对象的文档字符串并且没有让 Python 获取焦点?

【问题讨论】:

    标签: python interactive


    【解决方案1】:

    .__doc__ 是最好的选择。但是,您也可以使用inspect.getdoc 获取docstring。使用它的一个优点是,它可以从缩进的文档字符串中删除缩进以与代码块对齐。

    示例:

    In [21]: def foo():
       ....:     """
       ....:     This is the most useful docstring.
       ....:     """
       ....:     pass
       ....: 
    
    In [22]: from inspect import getdoc
    
    In [23]: print(getdoc(foo))
    This is the most useful docstring.
    
    In [24]: print(getdoc(str))
    str(object='') -> string
    
    Return a nice string representation of the object.
    If the argument is a string, the return value is the same object.
    

    【讨论】:

      【解决方案2】:

      您可以使用dir({在此处插入类名}) 获取类的内容,然后对其进行迭代,查找方法或其他内容。此示例在类 Task 中查找以名称 cmd 开头的方法并获取它们的文档字符串:

      command_help = dict()
      
      for key in dir( Task ):
          if key.startswith( 'cmd' ):
              command_help[ key ] = getattr( Task, key ).__doc__
      

      【讨论】:

        【解决方案3】:

        任何文档字符串都可以通过.__doc__ 属性获得:

        >>> print str.__doc__
        

        在 python 3 中,您需要括号来打印:

        >>> print(str.__doc__)
        

        【讨论】:

          猜你喜欢
          • 2017-06-09
          • 2021-01-16
          • 2022-09-29
          • 2016-07-09
          • 2012-11-06
          • 2023-02-25
          • 2015-05-11
          • 1970-01-01
          相关资源
          最近更新 更多