[英]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?
pydoc.doc
有output
参数,它应该是支持.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:
<class 'str'>
Python Library Documentation: class object in module builtins
class object
| The most base type
请注意, io.StringIO
行为通常与文件一样,但不会保存在磁盘上(=不是持久的)。 我以object
为例,因为它的文档很短。
为 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.