Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default text for Python input

Tags:

python

input

If I ask for user input, Python will let me use the arrow keys to move around what I typed and change it if necessary. For instance, when running the following program

user_input = input("file name -> ")
print(user_input)

I can use the left arrow to go back, change the 'G' to 'g'

file name -> thisIsAVeryLonGFileName.txt

and when I then hit Enter it prints

thisIsAVeryLongFileName.txt

Is there a way to prompt for user input with a default response already provided which then enables the user to use the arrow keys to modify the default response rather than having to type the whole response in? Basically, things should work just like above but without the user having to type anything in initially (instead it is provided by the program).

like image 652
rainerpm Avatar asked Mar 14 '26 11:03

rainerpm


1 Answers

This works well on Windows (requires pynput):

from pynput.keyboard import Key, Controller
keyboard = Controller()

def inputDefs(*args):
    if not args: args = ('','')
    prompt, default = str(args[0]),str(args[1])
    sys.stdout.write(prompt)
    sys.stdout.flush()
    for char in default: keyboard.press(char)
    return sys.stdin.readline().strip()

The first argument specifies the immutable text to display (like the argument of input), while the second argument specifies the modifiable default text. On Mac/Linux, there's the issue of arrow keys returning escape codes, so you can't use them to navigate to the middle of the default string, but you can still use backspace to delete characters and edit it.

Edit: A solution for Mac:

def editable_input(prompt, prefill=None):
    def hook():
        readline.insert_text(prefill)
        readline.redisplay()
    readline.set_pre_input_hook(hook)
    result = input(prompt + ': ')
    readline.set_pre_input_hook()
    return result 

adapted from this script

In order for this to work, use gnureadline:

import gnureadline as readline

like image 188
alediorisis Avatar answered Mar 15 '26 23:03

alediorisis



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!