获取已打印内容的文本内容python

use*_*835 4 python algorithm stdout

假设我打印以下代码

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))
Run Code Online (Sandbox Code Playgroud)

这将打印算法的结果,与用户输入的数字相匹配。

编辑:为了澄清我想要输出的原因,基本上我可以用“CLS”清除屏幕并重新打印我已经打印的所有内容,但是将偶数 x 值划掉,就像你应该用俄罗斯农民算法做的那样。

Iva*_*nko 5

它的全部内容是将您重新定义stdout为一些内存流。

您可以使用打印到string. 请参阅python2 文档 - 将字符串作为文件读取和写入python3 文档 - 用于处理流的核心工具

使用该字符串执行您要执行的操作,甚至可以使用常规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()
Run Code Online (Sandbox Code Playgroud)

代码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)
Run Code Online (Sandbox Code Playgroud)

whatWasPrinted 然后可以更改,打印到常规标准输出等。