[英]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.