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

标签 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))

这将打印算法的结果,与用户输入的数字相匹配。现在如果我希望获得一个包含所有已输出到 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/

相关文章:

python - 如何使用 ansi 转义码为 python 中的特定字符单元着色,其中字符单元位置由变量确定

algorithm - 具有作业排除和优先约束的多处理器调度

algorithm - 修改 LIST 使得一个元素大于之前所有元素的总和

python - 如何从 Python 中的 stdout 中删除行 - 在 SciTe、Idle、Eclipse 或其他带有控制台的编辑器中

python - 在 django 站点中嵌入 matplotlib 图

python - 这个装饰器在 python 中是如何工作的

python - MemoryError 将两个数据帧与 pandas 和 dasks 合并——我该怎么做?

c# - C# 中的快速子图像比较

c - 简单的 Bash-C 通信

bash - 用dd跳过stdin的前32k?