Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pydoc

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?

like image 237
ipmcc Avatar asked Jun 29 '12 16:06

ipmcc


4 Answers

pydoc.render_doc(thing) to get thing's help text as a string. Other parts of pydoc like pydoc.text and pydoc.html can help you write it to a file.

Using the -w modifier in linux will write the output to a html in the current directory, for example;

pydoc -w Rpi.GPIO

Puts all the help() text that would be presented from the command help(Rpi.GPIO) into a nicely formatted file Rpi.GPIO.html, in the current directory of the shell

like image 197
Aaron Altman Avatar answered Nov 13 '22 02:11

Aaron Altman


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')
like image 27
Michael0x2a Avatar answered Nov 13 '22 02:11

Michael0x2a


An old question but the newer recommended generic solution (for Python 3.4+) for writing the output of functions that print() to terminal is using 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)

Usage example:

write_help(int, 'test.txt')
like image 8
Chris_Rands Avatar answered Nov 13 '22 01:11

Chris_Rands


To get a "clean" text output, just as the built-in help() would deliver, and suitable for exporting to a file or anything else, you can use the following:

>>> 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'
like image 7
flexatone Avatar answered Nov 13 '22 01:11

flexatone