将 help() 函数内容的输出重定向到一个文件

Redirect the output of help() function's content to a file

我正在学习 selenium 并打算检查可用的方法。

browser = webdriver.Chrome()
browser.get(start_url)
help(browser)

帮助文档太长,我想把它们复制到一个文件中。

In [19]: with open("webdriver.md", "w") as file:
    ...:     file.write(help(browser))
    ...:     

TypeError: write() argument must be str, not None

pydoc 都没有帮助

In [23]: pydoc.writedoc("browser")
No Python documentation found for 'browser'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

如何将帮助(浏览器)写入纯文本文件。

您可以尝试更改当前的标准输出:

import sys
sys.stdout = open('webdriver.md', 'w')
help(browser)

Python3.4开始,也可以使用contextlib.redirect_stdout:

from contextlib import redirect_stdout
with redirect_stdout(open('webdriver.md', 'w')):
    help(browser)

bulit-in help() is a wrapper around pydoc.Helper, it writes to stdout by default,您可以暂时将 sys.stdout 重定向到文件:

>>> import contextlib
>>> with contextlib.redirect_stdout(open('browser_help.txt', 'w')):
...     help(browser)

或者您可以直接调用 pydoc.Helper,:

>>> import pydoc
>>> with open('browser_help.txt', 'w') as f:
...     h = pydoc.Helper(output=f)
...     h(browser)