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

5 投票
3 回答
2746 浏览
提问于 2025-04-15 13:34

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

我该如何获取一个对象的文档字符串,并且让 Python 把焦点抢走呢?

3 个回答

1

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

你可以使用 dir({在这里插入类名}) 来查看一个类里面的内容,然后你可以逐个查看这些内容,寻找方法或者其他东西。这个例子是查看一个叫 Task 的类,找出所有以 cmd 开头的方法,并获取它们的文档字符串:

command_help = dict()

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

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

>>> print str.__doc__

在 Python 3 中,打印内容时需要加上括号:

>>> print(str.__doc__)

撰写回答