How can I print the Python help page directly to stdout?

I am trying to write a Unix script that will allow me to print the Python help page for a given module. My code so far is below:

#!/usr/bin/env python

if __name__ == "__main__":
    import sys
    if sys.argv[1].endswith(".py"):
        __import__(sys.argv[1][:-3])
        help(sys.argv[1][:-3])
    else:
        __import__(sys.argv[1])
        help(sys.argv[1])

      

It works almost the way I want it to. Calling it on a module brings up the help page in a buffer, similar to calling less

. (In other words, it help

works exactly the same as when used in the interpreter.)

I would like to get rid of the buffer and print directly to stdout so that I can use the command with other Unix commands. I am wondering if there is a way to do this, and if so, how?

+3


source to share


2 answers


This works for me:



import pydoc

import math # test
print(pydoc.render_doc(math))

      

+5


source


Try it?

import pydoc

pydoc.help(xrange)

      



Or if you want it in string format

pydoc.getdoc(xrange)

      

+1


source







All Articles