Is it possible to prefill a input() in Python 3's Command Line Interface?

Question:

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

Asked By: Exeleration-G

||

Answers:

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

import readline

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
Answered By: Sven Marnach

I think you’re looking for something more smooth but an easy way to do it :

inputstring = input("Input your text here ('test' if ignored): ")
if inputstring == '' : inputstring = 'test'
Answered By: Yann