49

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

6
  • The short answer is no, but there's bound to be a curses or readline trick to do this. +1 for the question. Commented Dec 14, 2011 at 13:26
  • "Enter blargh (Default: 3)" doesn't do what you ask for, but solves the same problem. Commented Dec 14, 2011 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. Commented Dec 14, 2011 at 13:40
  • Duplicate of Show default value for editing on Python input possible? Commented Dec 14, 2011 at 13:55
  • 1
    That's Python. This is Python 3. Commented Aug 24, 2012 at 16:53

2 Answers 2

41

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
Sign up to request clarification or add additional context in comments.

4 Comments

Doesn't work on Mac OS X by default. Also, I had to change input() to raw_input() or it would throw "NameError: name 'what I typed' is not defined".
@EdwardFalk This has nothing to do with Mac OS X. You are using Python 2, while this question is about Python 3.
Ahh, missed that part.
note this doesn't work on python3.6 inside a Jupiter notebook, or in Pycharm console
-1

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'

1 Comment

Not really what was asked as with this response the user would still have to input everything, the question is asking for a way to use a pre set response and work with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.