40

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

Exeleration-G
  • 1,360
  • 16
  • 29
  • The short answer is no, but there's bound to be a `curses` or `readline` trick to do this. +1 for the question. – Fred Foo Dec 14 '11 at 13:26
  • "Enter blargh (Default: 3)" doesn't do what you ask for, but solves the same problem. – Lennart Regebro Dec 14 '11 at 13:31
  • @LennartRegebro: This doesn't serve exactly the same purpose. Imagine the user is supposed to enter a list of search paths, with some defaults predefined. The user will probably want to supplement the predefined list rather than replacing it. – Sven Marnach Dec 14 '11 at 13:40
  • Duplicate of [Show default value for editing on Python input possible?](http://stackoverflow.com/questions/2533120/show-default-value-for-editing-on-python-input-possible) – gecco Dec 14 '11 at 13:55
  • 1
    That's Python. This is Python 3. – Exeleration-G Aug 24 '12 at 16:53
  • Possible duplicate of [Show default value for editing on Python input possible?](https://stackoverflow.com/questions/2533120/show-default-value-for-editing-on-python-input-possible) – Florian Brucker May 20 '19 at 09:07

1 Answers1

36

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
andyhasit
  • 14,137
  • 7
  • 49
  • 51
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841