假设我打印了以下代码
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))
这将打印算法的结果,与用户输入的数字相匹配。现在如果我希望获得一个包含所有已输出到 python 控制台的变量,我该怎么做呢?
编辑:为了澄清我想要输出的原因,基本上我可以用“CLS”清除屏幕并重新打印我已经打印的所有内容,但偶数 x 值被划掉,就像你应该对俄语所做的那样农民算法。
最佳答案
这一切都是关于将您的 stdout
重新定义为某个内存流。
您可以使用打印到string
。参见 python2 docs - Reading and writing strings as file , python3 docs - Core tools for working with streams .
用那个字符串做你想做的事,甚至用常规的 print
打印它。
代码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()
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
然后可以更改,打印到常规标准输出等。
关于python - 获取已打印python的文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35779023/