所以我正在查看模块的help((文档,但很快意识到阅读小输出框中的文档非常乏味。因此,我尝试将 help(( 文档粘贴到另一个文件中,以便更清晰地阅读。
myfile = open("file.txt","w")
myfile.write(str(help(random)))
myfile.close()
它没有编写文档,而是粘贴了None
。
任何想法如何做到这一点?
答案是pydoc!。从控制台运行它:
$ pydoc [modulename] > file.txt
它基本上会将help()
命令的输出写入file.txt
我并不是建议你应该以这种方式阅读 Python 文档 - 但你可以这样做:你可以重定向stdout
并调用help
:
from contextlib import redirect_stdout
import random
with open('random_help.txt', 'w') as file:
with redirect_stdout(file):
help(random)
或者,更简单(如乔恩克莱门茨所建议的那样(:
from pydoc import doc
import random
with open('random_help.txt', 'w') as file:
doc(random, output=file)