我想在我的命令行应用程序中获取文档字符串,但每次调用内置的help()函数时,Python都会进入交互模式。
如何获取对象的文档字符串而不使Python获得焦点?
我想在我的命令行应用程序中获取文档字符串,但每次调用内置的help()函数时,Python都会进入交互模式。
如何获取对象的文档字符串而不使Python获得焦点?
任何文档字符串都可以通过 .__doc__
属性获取:
>>> print str.__doc__
>>> print(str.__doc__)
您可以使用dir(
{在此处插入类名})
来获取类的内容,然后迭代它,查找方法或其他内容。此示例查找一个名为Task
的类中以名称cmd
开头的方法,并获取它们的文档字符串:
command_help = dict()
for key in dir( Task ):
if key.startswith( 'cmd' ):
command_help[ key ] = getattr( Task, key ).__doc__
.__doc__
是最好的选择。但是,您也可以使用 inspect.getdoc
来获取 docstring
。使用此方法的一个优点是,它会从缩进对齐到代码块的 docstrings 中删除缩进。
示例:
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.