8

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?

1
  • If you are writing a command-line tool, the proper solution is often to have it read command-line arguments (sys.argv[1:]) instead of using input() interactively. Commented Aug 19, 2017 at 15:20

2 Answers 2

21

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)"
Sign up to request clarification or add additional context in comments.

4 Comments

You are right. Importing readline works. But it should work otherwise too since I have it installed. I am going to try a pip install to see if readline was installed properly.
"installed" is not the same as "loaded". You need to explicitly import the module to activate the readline support in the input function. The documentation says explicitly that the readline module must be "loaded".
Does this mean I need to import readline whenever I use input()? This was not needed on Windows...
I'm not familiar with Windows, but that is certainly what is implied by the documentation.
1

I use linux too and for any module you have to import it.

For example for the readline module I have to do

import readline

This applies to all modules even the os or sys module I have to do

import os
import sys

However this only applies to modules that you installed correctly. If you installed readline incorrectly not even

import readline

will work.

That means for you

python3 -c "import readline; x = input('enter a number '); print(x)"

if you are doing it straight from the console and this applies to not only readline but every other module that you have and will get.

Comments

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.