raw_input占位符?

时间:2012-10-07 20:51:55

标签: python

  

可能重复:
  Show default value for editing on Python input possible?

我想要raw_input要求确认某事。有没有办法在用户输入任何内容之前已经“输入”了文本?例如:

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

这可以与HTML中的<imput type="text" value="correct">进行比较。文本将自动为用户键入,但如果需要,他们可以添加或删除全部/部分文本。可以这样做吗?

1 个答案:

答案 0 :(得分:1)


示例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: ') 

测试代码:

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

<强>输出:

Test to correctness:

1 - correct
2 - not correct

Your answer is: correct
correct

示例2:

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

示例3(更复杂):

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

用法:

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

在Unix / Linux控制台(不是来自IDE)中工作