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

2019-02-07 17:44发布

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条回答
放我归山
2楼-- · 2019-02-07 18:28

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
查看更多
登录 后发表回答