Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text contents of what has been printed python

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.

like image 468
user2592835 Avatar asked Mar 03 '16 17:03

user2592835


1 Answers

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.

like image 66
Ivan Gritsenko Avatar answered Nov 14 '22 21:11

Ivan Gritsenko