Skip to content

Instantly share code, notes, and snippets.

@abingham
Last active May 22, 2023 20:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abingham/e19cfd042fefcd11ba60 to your computer and use it in GitHub Desktop.
Save abingham/e19cfd042fefcd11ba60 to your computer and use it in GitHub Desktop.
How to capture the output of Python's help() function.
import io
import sys
# Temporarily redirect stdout to a StringIO.
stdout = sys.stdout
s = io.StringIO()
sys.stdout = s
help(sys.intern)
# Don't forget to reset stdout!
sys.stdout = stdout
# Read the StringIO for the help message.
s.seek(0)
help_string = s.read()
print(help_string)
import sys
import pydoc
# And of course there's what's probably the correct way to do it!
s = pydoc.getdoc(sys.intern)
print(s)
@markcmiller86
Copy link

markcmiller86 commented Jun 21, 2021

If your goal is to test behvior of help(whatever) (which can, for example, ensure some extension library you've written behaves as expected within the Python interpreter), something more along the lines of the first form, capture_help.py is best. That said, this example doesn't work on Python 3 due to new way of handling unicode strings. You will get exceptions similar to...

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Applications/VisIt.app/Contents/Resources/2.10.2/../bin/../2.10.2/darwin-x86_64/lib/python/lib/python2.7/site.py", line 455, in __call__
    return pydoc.help(*args, **kwds)
  File "/Applications/VisIt.app/Contents/Resources/2.10.2/darwin-x86_64/lib/python/lib/python2.7/pydoc.py", line 1794, in __call__
    self.help(request)
  File "/Applications/VisIt.app/Contents/Resources/2.10.2/darwin-x86_64/lib/python/lib/python2.7/pydoc.py", line 1842, in help
    self.output.write('\n')
TypeError: unicode argument expected, got 'str'

However, this ref does seem to work in both Python 2 and 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment