input() :: Using Backspace And Arrow Keys

Question:

I have a python script that takes information from the user through the built in input() function.

My question is why do the backspace and arrow keys not function correctly and how can I fix it so they function as intended.

A simple example of the problem I am having…

#!/usr/bin/env python3
while 1:
  x=input("enter integer: ")
  y=int(x)*17
  print(y)

Here is an example of using it.

./tester 
enter integer: 3
51
enter integer: 17
289
enter integer: 172^[[D^[[D^H
Traceback (most recent call last):
  File "./tester", line 4, in <module>
    y=int(x)*17
ValueError: invalid literal for int() with base 10: '172x08'

In trying to remove the ‘1’ using the arrow keys and backspace, ^[[D^[[D^H came up instead of deleting moving left two spaces and removing the ‘1’, and the value crashed the program.

How do I fix this so all of the keys function as intended?

Asked By: Peregrine

||

Answers:

Look into the tkinter library:

http://wiki.python.org/moin/TkInter

There’s also a good discussion of the library here on SO:

Arrow key input code not working in tkinter

Answered By: Forhad Ahmed

Import the readline module from the standard library.
It automatically wraps stdin.

Answered By: t-8ch

To add to the answer from @t-8ch, here is an illustrative example:

import sys
print("Enter choice(1-4):")

res = sys.stdin.readline()  # used in place of input()
# to strip the new line from stdin like '4n' and then convert str to int
ch = int(res.strip()) 
Answered By: trohit
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.