我有一个python包,输出相当多的帮助文本: help(package)
我想将此帮助文本以其显示的格式导出到文件中 help(package)
我怎么能这样做?
Aar*_*man 15
pydoc.render_doc(thing)将东西的帮助文本作为字符串.像pydoc.text和pydoc.html这样的pydoc的其他部分可以帮助您将其写入文件.
例如,-w
在linux中使用修饰符会将输出写入当前目录中的html;
pydoc -w Rpi.GPIO
Run Code Online (Sandbox Code Playgroud)
将所有help()
将从命令中显示的文本help(Rpi.GPIO)
放入一个格式良好的文件Rpi.GPIO.html中,在shell的当前目录中
一个老问题,但较新的推荐通用解决方案(适用于 Python 3.4+)用于编写print()
终端正在使用的函数的输出contextlib.redirect_stdout
:
import contextlib
def write_help(func, out_file):
with open(out_file, 'w') as f:
with contextlib.redirect_stdout(f):
help(func)
Run Code Online (Sandbox Code Playgroud)
用法示例:
write_help(int, 'test.txt')
Run Code Online (Sandbox Code Playgroud)
要获得“干净”的文本输出,就像内置的 help() 将提供的一样,并且适合导出到文件或其他任何内容,您可以使用以下内容:
>>> import pydoc
>>> pydoc.render_doc(len, renderer=pydoc.plaintext)
'Python Library Documentation: built-in function len in module builtins\n\nlen(obj, /)\n Return the number of items in a container.\n'
Run Code Online (Sandbox Code Playgroud)
这有点hackish(并且在某处可能有更好的解决方案),但这有效:
import sys
import pydoc
def output_help_to_file(filepath, request):
f = open(filepath, 'w')
sys.stdout = f
pydoc.help(request)
f.close()
sys.stdout = sys.__stdout__
return
Run Code Online (Sandbox Code Playgroud)
然后...
>>> output_help_to_file(r'test.txt', 're')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5959 次 |
最近记录: |