2

So I was looking at the help() documentation of a module but soon realized it was very tedius to read the documentation in the small output box. So therefore I tried pasting the help() documentation to another file for more clearer reading.

myfile = open("file.txt","w") 
myfile.write(str(help(random)))
myfile.close()

Instead of the documentation being written, it instead pasted in None.

Any ideas how to do this?

  • 7
    Any reason why you don't read the files that are available online, i.e. the documentation? – Aran-Fey Aug 08 '18 at 14:45
  • 2
    [`help()`](https://docs.python.org/3/library/functions.html#help) does not return anything. –  Aug 08 '18 at 14:45
  • The [`random`](https://docs.python.org/3/library/random.html) documentation is available online. –  Aug 08 '18 at 14:46
  • I guess that works too; was interested if there was a way to paste it on a document. – TuftedDuckDebugger Aug 08 '18 at 14:48
  • 1
    Are you looking for [Redirect stdout to a file in Python?](https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python) – glibdud Aug 08 '18 at 14:48

2 Answers2

4

The answer is pydoc!. Run it from the console:

$ pydoc [modulename] > file.txt

and it will basically write the output of the help() command to file.txt

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
3

i'm not suggesting you should read the python documentation this way - but here is what you could do: you could redirect stdout and call help:

from contextlib import redirect_stdout
import random

with open('random_help.txt', 'w') as file:
    with redirect_stdout(file):
        help(random)

or, even simpler (as suggested by Jon Clements):

from pydoc import doc
import random

with open('random_help.txt', 'w') as file:
    doc(random, output=file)
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111