8
votes

I'm getting Arrow Key values in my Python Input using input().

This only happens during the time of execution of a Python Script. It doesn't happen if Input is taken from the Interpreter.

The Arrow Key values I'm referring to: Why does the terminal show "^[[A" "^[[B" "^[[C" "^[[D" when pressing the arrow keys in Ubuntu?

Contents of Script File:

s = input("Enter Something: ")
print(s)

Terminal Output:

$ python input_example.py 
Enter Something: Now Pressing Left Arrow Key^[[D^[[D^[[D^[[D
Now Pressing Left Arrow Key

I'm unable to navigate (or say change cursor position) left or right while writing input cause the Arrow Key Values Show up in the Input. Is there any way to avoid them? In Terminal, generally, one can change the cursor position, this problem doesn't happen unlike Python's input().

P.s. I don't want to change any settings in bash cause I'm trying to write a script that works in all consoles. I'm a noob so I don't understand many things. I hope this community can help me out.

2
Note that this is a behaviour of your shell, which decides to forward all input (including control characters). There is nothing Python can do about it.MisterMiyagi

2 Answers

10
votes

Found a way to prevent this! You just have to import the readline module

import readline

This will make the standard input() method utilize some of its utilities, enabling normal arrow-key usage and more.

0
votes

I found an answer:

https://www.codehaven.co.uk/python/using-arrow-keys-with-inputs-python/

Python's curses module is used for dealing with User Inputs. Then custom behavior is given to each Arrow Key. I'm not sure if the code is tested or not (semi-colons are used at end of the code) which Python doesn't allow.

Even if it is right, But it is very long and extreme for scripts made for automating small tasks. Is there any shorter alternative?