Pre-initialize raw_input with default value
input, linux, python, python-2.7
Solution
I actually found an answer myself after some more Googling. It can be done with `raw_input` when using the `readline` module as follows:
import readline
def pre_input_hook():
readline.insert_text('DefaultValue')
readline.redisplay()
readline.set_pre_input_hook(pre_input_hook)
while True:
line = raw_input('Prompt ("stop" to quit): ')
if line == 'stop':
break
print 'ENTERED: "%s"' % line
Or, to wrap it all in an easier-to-handle function based on jonrsharpe's comment:
import readline
DEFAULT_TEXT = ''
def default_hook():
"""Insert some default text into the raw_input."""
readline.insert_text(default_hook.default_text)
readline.redisplay()
readline.set_pre_input_hook(default_hook)
def raw_input_default(prompt, default=None):
"""Take raw_input with a default value."""
default_hook.default_text = DEFAULT_TEXT if default is None else default
return raw_input(prompt)
Problem
I have a "form" where I have a few `raw_input`s to get the user response. Now I want them to be pre-initialized with a default value. Is there any way to fill these `raw_input` fields? Or is there a good alternative to `raw_input` where that is possible? To clarify, I have something looking like this: ``` val = raw_input("Input val:") ``` What I want as output is the following: ``` Input val: default value ``` and I want the user to be able to erase or edit the default value as if they had written it themselves. Is there any way to do that?