1

Is there any way to save into a variable what print sends to the screen, so I will be able to print it back after erasing the screen?

Wolf
  • 9,679
  • 7
  • 62
  • 108
Daniel
  • 229
  • 1
  • 8

1 Answers1

3

Don't know why this question is being downvoted. Anyway, an answer from Raymond Hettinger on Twitter, utilises contextlib.redirect_stdout():

with open('help.txt', 'w') as f:
    with contextlib.redirect_stdout(f):
        help(pow)

Although, in this case the output is being redirected into a file, rather than a variable and is Python3, not 2.7.

From the docs, to capture that in a variable:

For example, the output of help() normally is sent to sys.stdout. You can capture that output in a string by redirecting the output to an io.StringIO object:

f = io.StringIO()
with redirect_stdout(f):
    help(pow)
s = f.getvalue()

This answer on SO shows another way to do it, and in Python2:

aneroid
  • 12,983
  • 3
  • 36
  • 66
  • Great answer, [much to learn](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout): until now I did `print(..., file=f)` by hand. – Wolf Feb 20 '20 at 15:03