As in the link :http://code.activestate.com/recipes/134892/ how shall i implement a backspace on stdout?
2 Answers
'\b' is the escape sequence for a backspace.
>>> print('123xx\b\b45')
12345
4 Comments
AJS
but i m reading char by char! this doesn't work if i use char by char reading!
Cyphase
@AJS, I see; I guess I answered too quickly. That said,
getch() shouldn't show the character you type. Which OS are you on?AJS
linux! and in my code i m printing out the char by char into stdout.... as sys.stdout.write(chr) where chr=getch().....
Cyphase
@AJS, normally you shouldn't fundamentally modify your question once it's been answered, but in this case, it's more a matter of it not being clear. Edit your question to show your code and explain further what you want to do.
Writing each character one at a time to sys.stdout should work. Using the referenced getch() you can see what it is returning for each key press:
import sys
from getch import getch
while True:
c = getch()
print '%r' % c
if c == 'q':
break
Typing backspace on my Linux system, getch() actually returns the DEL character, '\x7f' (not yet sure why). That can be translated to \b ('\x08') for Python.
import sys
from getch import getch
translations = string.maketrans('\x7f', '\b')
while True:
c = getch().translate(translations)
sys.stdout.write(c)
if c == 'q':
break
Probably there is a more elegant way of handling the character translations using the termios module.
Also, if you want backspace to clear the previously typed character you can translate '\x7f' to '\b \b'.