2

可能重复:
显示默认值以在 Python 输入上进行编辑可能吗?

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

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

这可以与<imput type="text" value="correct">HTML 相比。文本将自动为用户键入,但如果他们愿意,他们可以添加或删除全部/部分文本。这可以做到吗?

4

1 回答 1

2

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

于 2012-10-07T21:14:24.170 回答