Delete the last input row in Python

2020-01-29 16:16发布

问题:

I have the following code:

num = int(raw_input("input number: "))
print "\b" * 20

The console output looks like

input number: 10

I'd like to delete the text input number: 10 after the user presses ENTER. The backspace key \b can't do it.

回答1:

This will work in most unix and windows terminals ... it uses very simple ANSI escape.

num = int(raw_input("input number: "))
print "\033[A                             \033[A"    # ansi escape arrow up then overwrite the line

Please note that on Windows you may need to enable the ANSI support using the following http://www.windowsnetworking.com/kbase/windowstips/windows2000/usertips/miscellaneous/commandinterpreteransisupport.html

"\033[A" string is interpreted by terminal as move the cursor one line up.



回答2:

There are control sequences for 'word back' and 'line back' and the like that move the cursor. So, you could try moving the curser back to the start of the text you want to delete, and overriding it with spaces. But this gets complicated very quickly. Thankfully, Python has the standard curses module for "advanced terminal handling".

The only issue with this is that it isn't cross-platform at the moment - that module has never been ported to Windows. So, if you need to support Windows, take a look at the Console module.



回答3:

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 , "]"


回答4:

You can use os module

import os
os.system('clear')

The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window).

For IDLE:The best you could do is to scroll the screen down lots of lines, eg:

print "\n" * 100