首页 > 解决方案 > 在 Python 中清除打印

问题描述

所以我对编码和这个网站都很陌生,所以如果这很愚蠢,请多多包涵:

我正在做一个个人项目,想找到一种方法来清除 python 3.6 中的“print()”语句。例如:

print("The user would see this text.")

但如果我继续

print("The user would see this text.")
print("They would also see this text.")

有没有办法让用户只能看到第二个打印语句?

我已经看到推荐的“os.system('cls')”和“os.system('clear')”,但我得到了以下每个错误:

os.system('cls')

导致

sh:1:cls:未找到

os.system('clear')

导致

未设置 TERM 环境变量。

显然我错过了一些东西,但如果你知道它会非常感激。如果您知道另一种方法来做我在想的事情,那也很棒。感谢您花时间阅读本文,并感谢您的帮助。

编辑:我使用 Repl.it 作为我的 IDE。这可能是该网站的问题吗?

编辑:下载了一个新的IDE来检查,回复有效。如果您是新用户并使用 Repl.it,请注意某些代码无法正常运行。

标签: pythonpython-3.x

解决方案


我过去在现有行上“重新打印”某些内容的方法是直接使用标准输出,再加上回车将打印语句的光标带回行首(\r=回车return),而不是依赖于 print 函数。

在伪代码中:

# Send what you want to print initially to standard output, with a carriage return appended to the front of it.  
# Flush the contents of standard output.    
# Send the second thing you want to print to standard output.   

Python中的一个工作示例:

import sys  

sys.stdout.write('\rThe user would see this text')
sys.stdout.flush()
sys.stdout.write('\rThe user would also see this text')

编辑 图我会添加一个示例,您可以在其中实际看到代码工作,因为上面的工作示例将执行得如此之快,以至于您将永远看不到原始行。下面的代码包含一个睡眠,以便您可以看到它打印第一行,等待,然后使用第二个字符串重新打印该行:

import sys
from time import sleep

sys.stdout.write('\rThe user would see this text')
sys.stdout.flush()

sleep(2)

sys.stdout.write('\rThe user would also see this text')

推荐阅读