I'm trying to write a function in Python-3.x which will prompt the user to enter characters from the keyboard. I want all characters to be echoed normally except for the final newline, which terminates the input.
The following function does this properly except when backspace is entered. When the user types backspace, I want the rightmost character on the screen to be erased and the cursor to move one position to the left, just like in normal terminal input mode.
However, I can't get that to work properly here. Can anyone suggest a way to make this function work properly when the user is typing backspaces?
Thank you.
def read_until_newline(prompt=None):
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
if prompt:
sys.stdout.write(prompt)
sys.stdout.flush()
result = None
try:
while True:
try:
c = sys.stdin.read(1)
if c == '\n':
break
elif c == '^?' or c == '^H':
if result:
###
### How do I cause the rightmost
### character to be erased on the
### screen and the cursor to move
### one space to the left?
###
result = result[0:-1]
continue
sys.stdout.write(c)
sys.stdout.flush()
if result:
result += c
else:
result = c
except IOError:
pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
return result