Python获取文档字符串而不必进入交互模式

5

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

如何获取对象的文档字符串而使Python获得焦点?

3个回答

7

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

>>> print str.__doc__

在Python 3中,打印需要使用括号:
>>> print(str.__doc__)

3

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

command_help = dict()

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

1

.__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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接