I'm working on a Python script which at times requires input to be typed in by a user. I'm using bash on macOS Sierra.
To receive the input, I wrote the following:
import readline # gnureadline 6.3.8
START = '\033[91m\033[1m'
END = '\033[0m'
response = raw_input(START + 'Enter text: ' + END)
I am using the the ANSI escape sequences in START
and END
to visually differentiate the script's prompt from the user's text entry.
Unfortunately, once I start typing in the text, the program loses track of where the beginning of the user-inputted text actually is. The first carat below is where CTRLA now maps to, and the second is where CTRLE takes me. The arrow keys similarly believe the beginning and end of the user input are offset as shown.
Enter text: hello my name is
^ ^
I tried a few things to debug this.
I tried putting a newline between the prompt and the text entry, but that only made the offset worse.
If I only use the arrow keys and never things like CTRLA, CTRLE, option-arrow to navigate through the string, this works as expected. That said, given the length and complexity of the strings the user is entering, using only the arrow keys to move through the string will be painful for the user.
Most significantly, if I don't use START
and END
at all, this works perfectly. That said, the usability of the script drops -- it's hard to pick out the prompts from all the other text going by in the full version of this script.
Is there some trick for me to be able to use the ANSI escape sequences to format the prompt without messing up the user's ability to navigate using CTRLA, CTRLE, and option-arrow?
Separate printing the prompt and asking for input into two commands.
Python 3.x
print(START + 'Enter text: ' + END, end='')
response = input()
Python 2.x
import sys
# Use sys.stdout.write to avoid printing a trailing newline.
sys.stdout.write(START + 'Enter text: ' + END)
response = raw_input()