简体   繁体   English

是否有可能让 python PyDoc 模块返回包含内容的字符串,而不仅仅是打印它?

[英]Is it possibile to have python PyDoc module to return a string with the content instead of just printing it?

The function pydoc.doc() returns None , but i would like to capture the output the function prints, how can i do that using python code? The function pydoc.doc() returns None , but i would like to capture the output the function prints, how can i do that using python code?

pydoc.doc has output parameter which should be something supporting .write , you can use io.StringIO for that purpose following way: pydoc.docoutput参数,它应该是支持.write的东西,你可以使用io.StringIO来达到这个目的,方法如下:

import io
import pydoc
f = io.StringIO()
pydoc.doc(object, output=f)
f.seek(0)
objectdoc = f.read()
print(type(objectdoc))
print(objectdoc)

Output: Output:

<class 'str'>
Python Library Documentation: class object in module builtins

class object
 |  The most base type

Note that io.StringIO behaves generally just like file, but is not saved on disk (=is not persistent).请注意, io.StringIO行为通常与文件一样,但不会保存在磁盘上(=不是持久的)。 I used object as example as its documentation is short.我以object为例,因为它的文档很短。

Create a text buffer for output option of pydoc.doc为 pydoc.doc 的 output 选项创建一个文本缓冲区

import pydoc
from io import StringIO

buffer = StringIO()
pydoc.doc('math.cos', output=buffer)
text = buffer.getvalue()

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

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