Jump to content

Wikipedia:Reference desk/Archives/Computing/2014 November 16

From Wikipedia, the free encyclopedia
Computing desk
< November 15 << Oct | November | Dec >> November 17 >
Welcome to the Wikipedia Computing Reference Desk Archives
The page you are currently viewing is an archive page. While you can leave answers for any questions shown below, please ask new questions on one of the current reference desk pages.


November 16

[edit]

a = help(list.append) and help(list.append)

[edit]

Why are both method calls the same? Can't the 1st call save the help()? I see that help() returns None, but, what if I wanted to save the text of the help()?--Senteni (talk) 17:02, 16 November 2014 (UTC)[reply]

Help prints the docstring, which is a property of the object called __doc__
So you'd do
   a = list.append.__doc__
-- Finlay McWalterTalk 20:22, 16 November 2014 (UTC)[reply]
More generally (and for more complicated problems where there isn't a simple string like this to look at) you can capture your programs own prints (to stdout) by temporarily substituting a StringIO object in for sys.stderr. This is overkill for your current problem, but might come in handy later. An example (which accomodates the changes to StringIO done between python2 and python3) is:
import sys

try:
    import cStringIO
    new_stdout = cStringIO.StringIO()
except ImportError:
    import io
    new_stdout = io.StringIO()

old_stdout = sys.stdout

sys.stdout = new_stdout
help(list.append) # stuff that would normally print to stdout, usually the terminal
a = sys.stdout.getvalue()
sys.stdout.close()
sys.stdout = old_stdout

print("the output of help was >>{:s}<<".format(a))
-- Finlay McWalterTalk 21:06, 16 November 2014 (UTC)[reply]