将 help() 的内容存储在变量中:Python

Store contents of help() in a variable: Python

当我们使用 help() 函数时,它只显示文本,我无法将其存储在变量中...

h = help ( 'eval' ) # Doesn't work

那我该怎么办?如果我需要使用 PyDoc,我该怎么做?

__doc__ 属性就是您要找的:

>>> h = eval.__doc__
>>> h
'Evaluate the given source in the context of globals and locals.\n\nThe source may be a string representing a Python expression\nor a code object as returned by compile().\nThe globals must be a dictionary and locals can be any mapping,\ndefaulting to the current globals and locals.\nIf only globals is given, locals defaults to it.'

@Thomas 所说的使用 __doc__ 属性的简单方法

如果你想要help(something)给出的精确输出,那么使用

import contextlib
import io

out_io = io.StringIO()

with contextlib.redirect_stdout(out_io):
    help(eval)

out_io.seek(0)
# out has what you're looking for
out = out_io.read()

解释:

contextlib.redirect_stdout 临时修补 sys.stdout 到您传递给它的任何文件,例如对象

我们传入一个 StringIO 对象作为类文件对象,它得到 printed 写入的值

然后最后 StringIO 对象被寻找回到起点并从

读取