Delete the last input row in Python

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.


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.


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.


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