Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input() :: Using Backspace And Arrow Keys

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: '172\x08'

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?

like image 682
Peregrine Avatar asked Feb 10 '13 09:02

Peregrine


2 Answers

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

like image 178
t-8ch Avatar answered Oct 12 '22 22:10

t-8ch


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

like image 30
Forhad Ahmed Avatar answered Oct 13 '22 00:10

Forhad Ahmed