1

As in the link :http://code.activestate.com/recipes/134892/ how shall i implement a backspace on stdout?

1
  • What does the link have to do with this? Commented Aug 17, 2015 at 0:48

2 Answers 2

1

'\b' is the escape sequence for a backspace.

>>> print('123xx\b\b45')
12345
Sign up to request clarification or add additional context in comments.

4 Comments

but i m reading char by char! this doesn't work if i use char by char reading!
@AJS, I see; I guess I answered too quickly. That said, getch() shouldn't show the character you type. Which OS are you on?
linux! and in my code i m printing out the char by char into stdout.... as sys.stdout.write(chr) where chr=getch().....
@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.
0

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'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.