Is it possible to prefill a input() in Python 3

2019-02-07 17:45发布

问题:

I'm using Python 3.2 on Ubuntu 11.10 (Linux). A piece of my new code looks like this:

text = input("TEXT=")

Is it possible to get some predefined string after the prompt, so I can adjust it if needed? It should be like this:

python3 file
TEXT=thepredefinedtextishere

Now I press Backspace 3 times

TEXT=thepredefinedtextish

Now I press Enter, and the variable text should be thepredefinedtextish

回答1:

If your Python interpreter is linked against GNU readline, input() will use it. In this case, the following should work:

def input_with_prefill(prompt, text):
    def hook():
        readline.insert_text(text)
        readline.redisplay()
    readline.set_pre_input_hook(hook)
    result = input(prompt)
    readline.set_pre_input_hook()
    return result