2

Possible Duplicate:
Show default value for editing on Python input possible?

I'd like to have a raw_input to ask for confirmation on something. Is there a way to have text already "entered" before the user types anything? For example:

>>> x = raw_input('1 = 2. Correct or incorrect? ', 'correct')
1 = 2. Correct or incorrect? correct

This could be compared to <imput type="text" value="correct"> in HTML. The text would be automatically typed for the user, but they could add to or erase all/part of it if they desire. Can this be done?

Community
  • 1
  • 1
tkbx
  • 15,602
  • 32
  • 87
  • 122

1 Answers1

2

Example 1:

def make_question(question, *answers):
    print question
    print
    for i, answer in enumerate(answers, 1):
        print i, '-', answer

    print
    return raw_input('Your answer is: ') 

Test code:

answer = make_question('Test to correctness:', 'correct', 'not correct')
print answer

Outputs:

Test to correctness:

1 - correct
2 - not correct

Your answer is: correct
correct

Example 2:

input = raw_input('Are you sure?: [Y]') # [Y] - YES by default
if input.lower() in ['n', 'no']:
    exit() # or return...

Example 3 (more complex):

import termios, fcntl, sys, os

def prompt_user(message, *args):
    fd = sys.stdin.fileno()
    oldterm = termios.tcgetattr(fd)
    newattr = termios.tcgetattr(fd)
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, newattr)
    oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

    sys.stdout.write(message.strip())
    sys.stdout.write(' [%s]: ' % '/'.join(args))

    choice = 'N'
    lower_args = [arg.lower() for arg in args]
    try:
        while True:
            try:
                c = sys.stdin.read(1)
                if c.lower() in lower_args:
                    sys.stdout.write('\b')
                    sys.stdout.write(c)
                    choice = c

                if c == '\n':
                    sys.stdout.write('\n')
                    break

            except IOError: 
                pass
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

    return choice

Usage:

print prompt_user('Are you sure?', 'Y', 'N', 'A', 'Q')

Worked in Unix/Linux console (not from IDE)

akaihola
  • 26,309
  • 7
  • 59
  • 69
Usman Salihin
  • 291
  • 1
  • 8
  • 6
    it doesn't handle "they could add to or erase all/part of it if they desire" part of the question – jfs Oct 07 '12 at 21:15
  • Care to add some comment to your code? How does it works? Some useful link maybe? – Yaroslav Oct 07 '12 at 21:16
  • @J.F.Sebastian didn't try it, thought the [string] was the default text. Thanks for the notice. – tkbx Oct 07 '12 at 21:51