例 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 からではありません)。