繁体   English   中英

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

[英]Store contents of help() in a variable: Python

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

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

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

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

如果您想要确切的 output 作为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 修补到任何文件,如 object 你传递它

我们将StringIO object 作为类似文件的 object 传入,它会获取写入的打印

然后最后将StringIO寻回开始并从

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM