4

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.

Number1
  • 391
  • 2
  • 4
  • 22
user1561108
  • 2,666
  • 9
  • 44
  • 69
  • where/how are you taking input? – Padraic Cunningham Jun 18 '15 at 20:54
  • I could @AnandSKumar but I am experimenting with how the stdout works and if I were to create a custom file-like object to possibly redirect stdout to that object. – user1561108 Jun 18 '15 at 21:10
  • @user1561108, are you actually trying to store all output? – Padraic Cunningham Jun 18 '15 at 21:12
  • @PadraicCunningham just a learning exercise. What I want to do is suppress output by setting sys.stdout to a dummy file-like object. So far my class implements flush and write with a pass but when I set sys.stdout to an instance of it my app complains at runtime it is a calling flush on a NoneType object. – user1561108 Jun 18 '15 at 21:24

2 Answers2

4

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.

tynn
  • 38,113
  • 8
  • 108
  • 143
2

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))
Number1
  • 391
  • 2
  • 4
  • 22
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321