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.
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.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With