Python Get Docstring Without Going into Interactive Mode

青春壹個敷衍的年華 提交于 2019-12-07 06:49:20

问题


I want to grab the docstring in my commandline application, but every time I call the builtin help() function, Python goes into interactive mode.

How do I get the docstring of an object and not have Python grab focus?


回答1:


Any docstring is available through the .__doc__ property:

>>> print str.__doc__

In python 3, you'll need parenthesis for printing:

>>> print(str.__doc__)



回答2:


You can use dir({insert class name here}) to get the contents of a class and then iterate over it, looking for methods or other stuff. This example looks in a class Taskfor methods starting with the name cmd and gets their docstring:

command_help = dict()

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



回答3:


.__doc__ is the best choice. However, You can also use inspect.getdoc to get docstring. One advantage of using this is, it removes indentation from docstrings that are indented to line up with blocks of code.

Example:

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.


来源:https://stackoverflow.com/questions/1270615/python-get-docstring-without-going-into-interactive-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!