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?
Asked
Active
Viewed 284 times
1
-
4If you are printing on the screen, you should already have it stored. Can you specify where is the information on the screen from? – TYZ Oct 02 '18 at 19:01
-
What have you tried? If you show your attempt and circumstances it'll be easier to help. – Matt Messersmith Oct 02 '18 at 19:01
-
What screen are you talking about? Please give more details. – Irfanuddin Oct 02 '18 at 19:01
-
May be this is what you are looking for: https://stackoverflow.com/questions/5309978/sprintf-like-functionality-in-python – Forever Learner Oct 02 '18 at 19:04
1 Answers
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