12

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.

1
  • 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. Commented Apr 4, 2020 at 9:33

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thnx it helped alot
1

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?

1 Comment

Try to be little descriptive and expressive in answers, A reference link only could be written in comment itself.

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.