31

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?

1
  • 5
    Do you know about the pydoc module? Commented Jun 29, 2012 at 16:36

14 Answers 14

23

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

Sign up to request clarification or add additional context in comments.

3 Comments

This is actually a bit easier than the selected answer.
I've found the selected answer to be not very good, using this post, I did a bit of research into pydocs and edited this answer with my exact solution
Nice, thanks. I didn't know there was a command line utility to go with it.
13

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')

1 Comment

we can also use this function to get the help of the class of a variable: so if you have a variable v and you would like to write the help of its class, you may write: output_help_to_file(r'test.txt', v)
9

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')

4 Comments

does not work with python 3.8.5 on ubuntu 20: the help is still printed on the screen
@xtof54 Are you sure? It's still recommend for Python 3.9 docs.python.org/3/library/…
Yes, I'm sure that when I type these commands on my computer, then it does not work. Now, I might have some special configuration I'm not aware of that prevents it to work in my specific case, and may be it's working well for most other people, I don't know...
For me this works when put into a Python file and executed; If you want to run it in the interpreter then you need to manually call __enter__() on the redirect_stdout: fp = open('temp.txt', 'wt') contextlib.redirect_stdout(fp).__enter__() help(package)
8

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'

Comments

2

If you do help(help) you'll see:

Help on _Helper in module site object:

class _Helper(__builtin__.object)
 |  Define the builtin 'help'.
 |  This is a wrapper around pydoc.help (with a twist).

[rest snipped]

So - you should be looking at the pydoc module - there's going to be a method or methods that return what help(something) does as a string...

Comments

1

Sometimes I wonder why the solution needs to be so complicated... Here is an example you can do from Bash in a 1-liner:

 python -c "import cloudflare; help(cloudflare)" >> cloudflare.txt

Result:

enter image description here

Simple....

1 Comment

This looks considerably more complicated than the most upvoted answer, which would suggest pydoc -w cloudflare?
0

In Windows, just open up a Windows Command Line window, go to the Lib subfolder of your Python installation, and type

python pydoc.py moduleName.memberName > c:\myFolder\memberName.txt

to put the documentation for the property or method memberName in moduleName into the file memberName.txt. If you want an object further down the hierarchy of the module, just put more dots. For example

python pydoc.py wx.lib.agw.ultimatelistctrl > c:\myFolder\UltimateListCtrl.txt

to put the documentation on the UltimateListCtrl control in the agw package in the wxPython package into UltimateListCtrl.txt.

Comments

0

pydoc already provides the needed feature, a very well-designed feature that all question-answering systems should have. The pydoc.Helper.init has an output object, all output being sent there. If you use your own output object, you can do whatever you want. For example:

class OUTPUT():

def __init__(self):
    self.results = []
def write(self,text):
    self.results += [text]
def flush(self):
    pass
def print_(self):
    for x in self.results: print(x)
def return_(self):
    return self.results
def clear_(self):
    self.results = []

when passed as

O = OUTPUT() # Necessarily to remember results, but see below.

help = pydoc.Helper(O)

will store all results in the OUTPUT instance. Of course, beginning with O = OUTPUT() is not the best idea (see below). render_doc is not the central output point; output is. I wanted OUTPUT so I could keep large outputs from disappearing from the screen using something like Mark Lutz' "More". A different OUTPUT would allow you to write to files.

You could also add a "return" to the end of the class pydoc.Helper to return the information you want. Something like:

if self.output_: return self.output_

should work, or

if self.output_: return self.output.return_()

All of this is possible because pydoc is well-designed. It is hidden because the definition of help leaves out the input and output arguments.

Comments

0

Selected answer didn't work for me, so I did a little more searching and found something that worked on Daniweb. Credit goes to vegaseat. https://www.daniweb.com/programming/software-development/threads/20774/starting-python/8#post1306519

# simplified version of sending help() output to a file
import sys
# save present stdout
out = sys.stdout
fname = "help_print7.txt"
# set stdout to file handle
sys.stdout = open(fname, "w")
# run your help code
# its console output goes to the file now
help("print")
sys.stdout.close()
# reset stdout
sys.stdout = out

1 Comment

This is exactly the same as the accepted answer.
0

The simplest way to do that is via using

sys module

it opens a data stream between the operation system and it's self , it grab the data from the help module then save it in external file

file="str.txt";file1="list.txt"
out=sys.stdout
sys.stdout=open('str_document','w')
help(str)
sys.stdout.close

Comments

0

The cleanest way

Assuming help(os)

Step 1 - In Python Console

 import pydoc 
 pydoc.render_doc(os, renderer=pydoc.plaintext)` 
 
 #this will display a string containing help(os) output 

Step 2 - Copy string

Step 3 - On a Terminal

echo "copied string" | tee somefile.txt 

If you want to write Class information in a text file. Follow below steps

  1. Insert pdb hook somewhere in the Class and run file

    import pdb; pdb.set_trace()

  2. Perform step 1 to 3 stated above

Comments

0

Using the command line we can get the output directly and pipe it to whatever is useful.

python -m pydoc ./my_module_file.py

-- the ./ is important, it tells pydoc to look at your local file and not attempt to import from somewhere else.

If you're on the mac you can pipe the output to pbcopy and paste it into a documentation tool of your choice.

python -m pydoc ./my_module_file.py | pbcopy

Comments

0

Just write a tiny script that calls the help() you want to capture and run it from the command line with output redirection.

Comments

0

Other answers did not work for me on Windows within an interactive python session. I cannot do it from a command line as I need help on a COM object. I used the output argument mentioned by Clifford

def help_to_file(func, out_file="function_help.txt"):
    try:
        with open(out_file, "w") as f:
            h2f = pydoc.Helper(output=f)
            h2f(func)
        print(f"Help for '{func}' written to '{out_file}'")
    except Exception as e:
        print(f"Error writing help: {e}")

Then to use it:

help_to_file(str, "_str.txt")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.