8

Lets say I print the following code

print("""
THE RUSSIAN PEASANT ALGORITHM
-----------------------------
times two values x and y together


""")

x=int(raw_input("raw_input x: "))
y=int(raw_input("raw_input y: "))

print("x"+" "*(10)+"y")

while x!=1:
      x=x/2
      y=y*2

      print(str(x)+" "*10+str(y))

This prints the results of an algorithm, appropiately to the numbers that the user enterred.Now if I wished to get a variable containing all that had been outputted to the python console, how would I go about that?

EDIT: To clarify the reason I want the output if so basically I can clear the screen with "CLS" and reprint everything I've already printed but with the even x values crossed out as you are supposed to do with the russian peasant algorithm.

user2592835
  • 1,547
  • 5
  • 18
  • 26

4 Answers4

9

Its all about redefine your stdout to some inmemory stream.

You can use printing to string. See python2 docs - Reading and writing strings as file, python3 docs - Core tools for working with streams.

Do what you what with that string even print it with regular print.


Code Python2:

import sys
import StringIO
old_stdout = sys.stdout # Memorize the default stdout stream
sys.stdout = buffer = StringIO.StringIO()

print('123')
a = 'HeLLo WorLd!'
print(a)
# Call your algorithm function.
# etc...

sys.stdout = old_stdout # Put the old stream back in place

whatWasPrinted = buffer.getvalue() # Return a str containing the entire contents of the   buffer.
print(whatWasPrinted) # Why not to print it?
buffer.close()

Code Python3:

import sys
import io

old_stdout = sys.stdout # Memorize the default stdout stream
sys.stdout = buffer = io.StringIO()

print('123')
a = 'HeLLo WorLd!'
print(a)
# Call your algorithm function.
# etc...

sys.stdout = old_stdout # Put the old stream back in place

whatWasPrinted = buffer.getvalue() # Return a str containing the entire contents of the buffer.
print(whatWasPrinted) # Why not to print it?
print(123)

whatWasPrinted then can be changed, printed to regular stdout, etc.

Community
  • 1
  • 1
Ivan Gritsenko
  • 4,166
  • 2
  • 20
  • 34
2

you can do this by writing in a text file:

sys.stdout = open("test.txt", "w")

##    Your Code    ##
    
sys.stdout.close()

if you need it in your program you can read from the text file.

printed_text=open("test.txt", "r").readlines()
Adak Vira
  • 21
  • 2
1

What you seem to want is to tee the output, if we make a minor tweak to the Tee implementation here using a tempfile you can write to a TemporaryFile then get the output from that:

import sys
from tempfile import TemporaryFile

class Tee(object):
    def __init__(self):
        self.file = TemporaryFile()
        self.stdout = sys.stdout
        sys.stdout = self

    def __del__(self):
        sys.stdout = self.stdout
        self.file.close()

    def write(self, data):
        self.file.write(data)
        self.file.write(data.rstrip()+"\n")
        self.stdout.flush()
t = Tee()
print("""
THE RUSSIAN PEASANT ALGORITHM
-----------------------------
times two values x and y together


""")

x = int(raw_input("raw_input x: "))
y = int(raw_input("raw_input y: "))    
print("x" + " " * (10) + "y")   
while x != 1:
    x = x / 2
    y = y * 2  
    print(str(x) + " " * 10 + str(y))   
t.file.seek(0)
print(t.file.read())
Community
  • 1
  • 1
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Traceback (most recent call last): File "C:/Python27/DECISION/Section 1/Russian_Peasant_Algorithm.py", line 59, in print(t.file.read()) File "C:/Python27/DECISION/Section 1/Russian_Peasant_Algorithm.py", line 20, in write self.file.write(data) IOError: [Errno 0] Error >>> – user2592835 Mar 03 '16 at 17:54
  • That would be because you are using windoze, try it now – Padraic Cunningham Mar 03 '16 at 17:58
-1

I'm not sure why you want to do this, so this might not help you, but it's possible to get all values printed in console by executing your script from another script.

in a new file :

import subprocess
linetorun = ["python", "yourscript.py"]
proc= subprocess.Popen(linetorun,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
printedtoconsole,errormessage=proc.communicate()
with open("output.txt","w+") as outfile:
    f.write(x)

should do the trick. communicate() with the options set in Popen will give you the console output. This might need some adaptation for unix.

WNG
  • 3,705
  • 2
  • 22
  • 31