pythonpydoc

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


I am learning selenium and intend to check methods available.

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

The help document is too long so I'd like to copy them to a file.

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

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

Either pydoc is not helpful

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.

How could I write help(browser) to a plain text file.


Solution

  • bulit-in help() is a wrapper around pydoc.Helper, it writes to stdout by default, you could temporarily redirecting sys.stdout to a file:

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

    or you could call pydoc.Helper directly, :

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