我想raw_input
要求确认某事。有没有办法在用户输入任何内容之前“输入”文本?例如:
>>> x = raw_input('1 = 2. Correct or incorrect? ', 'correct')
1 = 2. Correct or incorrect? correct
这可以与<imput type="text" value="correct">
HTML 相比。文本将自动为用户键入,但如果他们愿意,他们可以添加或删除全部/部分文本。这可以做到吗?
我想raw_input
要求确认某事。有没有办法在用户输入任何内容之前“输入”文本?例如:
>>> x = raw_input('1 = 2. Correct or incorrect? ', 'correct')
1 = 2. Correct or incorrect? correct
这可以与<imput type="text" value="correct">
HTML 相比。文本将自动为用户键入,但如果他们愿意,他们可以添加或删除全部/部分文本。这可以做到吗?
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
input = raw_input('Are you sure?: [Y]') # [Y] - YES by default
if input.lower() in ['n', 'no']:
exit() # or return...
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)