-4

Is it possible to pre-specify the response to a series of raw_input questions within a program?

as in, if somewhere in my program I have:

response = raw_input("Enter something: ")

can i specify before the program begins that I would like to have "something" entered at the command line?

sgchako
  • 109
  • 1
  • 8

2 Answers2

0

As I understand it, you'd like your program to instantly show something like this:

Enter something: something _

(Where _ is the shell's caret)

So that if you pressed enter, raw_input would return the string "something" - or you could press Backspace and edit the pre-filled input.


The simple answer is no, you cannot do this. The problem is that it is not Python handling the input at that point - it is your shell (bash, cmd, etc.) Only after you type something and press enter is that input "delivered" back to Python.

A library like readline will allow for something like what you want, but will only work on versions of Python linked against readline (usually Linux). See this answer for more.


An alternative that many programs use is to show a default value after the prompt, which is assumed if no input is given. This function should mimic this behavior:

def raw_input_default(prompt, default):
    result = raw_input('{0} [{1}] '.format(prompt, default))
    if result == '':
        result = default
    return result

Usage:

>>> print raw_input_default('Enter name:', 'Joe')
Enter name: [Joe] John
John
>>> print raw_input_default('Enter name:', 'Joe')
Enter name: [Joe]
Joe
Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • If this is indeed what the author is asking, you can get something awfully similar. See [this](http://stackoverflow.com/a/20351345/2297365) answer. It shows some value that you type over, and it's trivially simple to adapt so that you can press enter and have the response take on the default. – huu May 20 '14 at 05:19
  • @HuuNguyen I wouldn't say "awfully similar". For example this doesn't provide the edit capabilities that a truly pre-filled solution would. – Jonathon Reinhart May 20 '14 at 05:20
0

To implement default when you prompt the user, simply check if the response is empty - and set your default. This is typical displayed like this:

value = raw_input('Would you like to continue? [Y/n]: ')

The capital letter signifies the default value if no value is set, and the n is the optional value that the user can enter:

value = raw_input('Would you like to continue? [Y/n]: ')

# Set the default to 'Y'
if not len(value.strip()):
     result = 'Y'
else:
     result = value
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284