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

前端 未结 9 1042
时光取名叫无心
时光取名叫无心 2020-12-15 20:19

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 w

9条回答
  •  囚心锁ツ
    2020-12-15 20:29

    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.

提交回复
热议问题