Search code examples
pythonpydoc

How do I export the output of Python's built-in help() function


I've got a python package which outputs considerable help text from: help(package)

I would like to export this help text to a file, in the format in which it's displayed by help(package)

How might I go about this?


Solution

  • This is a bit hackish (and there's probably a better solution somewhere), but this works:

    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
    

    And then...

    >>> output_help_to_file(r'test.txt', 're')