How to reattach sys.stdout to console window in python?

9k views Asked by At

My python 3 doodling went like this:

import io, sys
sys.stdout = io.StringIO()
# no more responses to python terminal funnily enough

My question is how to reattach so when I pass in 1+1 for example it'll return with 2 to the console?

This is in the python interpreter on 32-bit python running on windows 7 64 bit.

2

There are 2 answers

0
tynn On BEST ANSWER

You're looking for sys.__stdout__:

It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object.

0
Padraic Cunningham On

I'm not sure how you are taking input but this will do what you want:

import io, sys

f = io.StringIO()
sys.stdout = f

while True:
    inp = input()
    if inp == "1+1":
        print(inp)
        break
sys.stdout = sys.__stdout__
print(eval(f.getvalue()))

Or get the last value of inp:

import io, sys

f = io.StringIO()
sys.stdout = io.StringIO()

while True:
    inp = input()
    if inp == "1+1":
        print(inp)
        break
sys.stdout = sys.__stdout__
print(eval(inp))

Or iterate over stdin:

import io, sys

sys.stdout = io.StringIO()
for line in sys.stdin:
    if line.strip() == "1+1":
        print(line)
        break
sys.stdout = sys.__stdout__
print(eval(line))