[英]Python Get Docstring Without Going into Interactive Mode
我想在命令行应用程序中获取docstring,但每次调用builtin help()函数时,Python都会进入交互模式。
如何获取对象的文档字符串而没有 Python抓取焦点?
任何docstring都可以通过.__doc__
属性获得:
>>> print str.__doc__
在python 3中,您需要使用括号进行打印:
>>> print(str.__doc__)
您可以使用dir(
{insert class name here} )
获取类的内容,然后迭代它,查找方法或其他内容。 此示例在类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
。 使用它的一个优点是,它删除了缩进以与代码块对齐的文档字符串的缩进。
例:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.