问题
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