【发布时间】:2012-06-05 11:27:03
【问题描述】:
我有以下代码:
num = int(raw_input("input number: "))
print "\b" * 20
控制台输出看起来像
input number: 10
我想在用户按下ENTER 后删除文本input number: 10。退格键\b 不行。
【问题讨论】:
-
您在哪个操作系统下工作?
我有以下代码:
num = int(raw_input("input number: "))
print "\b" * 20
控制台输出看起来像
input number: 10
我想在用户按下ENTER 后删除文本input number: 10。退格键\b 不行。
【问题讨论】:
你可以使用os模块
import os
os.system('clear')
“cls”和“clear”是清除终端(即DOS 提示符或终端窗口)的命令。
对于 IDLE:你能做的最好的就是将屏幕向下滚动很多行,例如:
print "\n" * 100
【讨论】:
有'word back'和'line back'等控制序列来移动光标。因此,您可以尝试将光标移回要删除的文本的开头,并用空格覆盖它。但这很快就会变得复杂。值得庆幸的是,Python 具有用于“高级终端处理”的标准 curses module。
唯一的问题是它目前不是跨平台的 - 该模块从未移植到 Windows。因此,如果您需要支持 Windows,请查看 Console module。
【讨论】:
curses 模块中的哪些函数会有所帮助吗?
curses.initscr() 创建window 对象,并使用窗口方法而不是print 和raw_input 进行I/O。那么当你想删除一整行时,你需要确保光标在该行的某处,并在窗口上调用.deleteln()。
这适用于大多数 unix 和 windows 终端...它使用非常简单的 ANSI 转义。
num = int(raw_input("input number: "))
print "\033[A \033[A" # ansi escape arrow up then overwrite the line
请注意,在 Windows 上,您可能需要使用以下命令启用 ANSI 支持 http://www.windowsnetworking.com/kbase/windowstips/windows2000/usertips/miscellaneous/commandinterpreteransisupport.html
"\033[A" 字符串被终端解释为将光标向上移动一行。
【讨论】:
import sys
print "Welcome to a humble little screen control demo program"
print ""
# Clear the screen
#screen_code = "\033[2J";
#sys.stdout.write( screen_code )
# Go up to the previous line and then
# clear to the end of line
screen_code = "\033[1A[\033[2K"
sys.stdout.write( screen_code )
a = raw_input( "What a: " )
a = a.strip()
sys.stdout.write( screen_code )
b = raw_input( "What b: " )
b = b.strip()
print "a=[" , a , "]"
print "b=[" , b , "]"
【讨论】: