Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow keys not working while entering data for input() function

Tags:

python

linux

In linux, the arrow keys don't work when I try to enter data for an input() function. I get escape characters. See below (when I pressed left arrow key).

dp@hp:~$ python3 -c "x = input('enter a number '); print(x)"
enter a number 123^[[D^[[D

I have readline installed (I am able to import it in the python shell). The arrow keys work fine in the interactive interpreter but not in the above case (or when I execute input() from a script).

What could be the reason?

like image 228
debashish Avatar asked Jun 07 '26 02:06

debashish


1 Answers

The documentation says:

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

In your example, you haven't loaded the readline module. Compare the behavior of this:

x = input('enter a number:')
print(x)

To this:

import readline
x = input('enter a number:')
print(x)

The second example will behave as you expect (readline support is active, arrow keys work, etc) while the first example will not have readline support.

On the command line, this would be:

python3 -c "import readline; x=input('enter a number '); print(x)"
like image 73
larsks Avatar answered Jun 10 '26 06:06

larsks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!