Last active
May 22, 2023 20:55
-
-
Save abingham/e19cfd042fefcd11ba60 to your computer and use it in GitHub Desktop.
How to capture the output of Python's help() function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...However, this ref does seem to work in both Python 2 and 3.