制限時間内のキー入力検査
Posted feedbacks - Python
ちょっと冗漫ですが、こんなところで。 # try節からreturnしてもfinally通るんだっけかな。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import termios, sys, tty, select
def InputChecker(N, S):
sys.stdout.write('input(%s) => ' % S)
sys.stdout.flush()
fd = sys.stdin.fileno()
poll = select.poll()
poll.register(fd, select.POLLIN)
attr = termios.tcgetattr(fd)
tty.setcbreak(fd)
s = ''
flg = False
try:
while True:
t = poll.poll(N * 1000)
if not t:
if not flg:
continue
print '\nresult => TIME OUT'
break
flg = True
c = sys.stdin.read(1)
sys.stdout.write(c)
sys.stdout.flush()
if c == '\n':
if S == s:
print 'result => OK'
else:
print 'result => NG'
break
s += c
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, attr)
poll.unregister(fd)
InputChecker(5, 'ABCDEF')
|
少しだけ改良。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | from sys import stdin, stdout
import tty, select
def write(s):
stdout.write(s)
stdout.flush()
def InputChecker(N, S):
write('input(%s) => ' % S)
poll = select.poll()
poll.register(stdin, select.POLLIN)
attr = tty.tcgetattr(stdin)
tty.setcbreak(stdin)
s = ''
try:
while True:
l = poll.poll(N * 1000)
if not l:
if not s:
continue
write('\nresult => TIME OUT\n')
return
c = stdin.read(1)
write(c)
if c == '\n':
write('result => %s\n' % ('OK' if S == s else 'NG'))
return
s += c
finally:
tty.tcsetattr(stdin, tty.TCSADRAIN, attr)
poll.unregister(stdin)
InputChecker(5, 'ABCDEF')
|
条件6の対応もれを訂正。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | from sys import stdin, stdout
import tty, select
def write(s):
stdout.write(s)
stdout.flush()
def InputChecker(N, S):
write('input(%s) => ' % S)
poll = select.poll()
poll.register(stdin, select.POLLIN)
attr = tty.tcgetattr(stdin)
tty.setcbreak(stdin)
s = ''
timeout = False
try:
while True:
if not poll.poll(N * 1000):
if not s:
continue
timeout = True
c = stdin.read(1)
write(c)
if c == '\n':
write('result => %s\n' % ('TIME OUT' if timeout else 'OK' if S == s else 'NG'))
return
s += c
finally:
tty.tcsetattr(stdin, tty.TCSADRAIN, attr)
poll.unregister(stdin)
InputChecker(5, 'ABCDEF')
|




raynstard
#3420()
Rating0/2=0.00
関数 InputCheckerは、以下の仕様を満たしてください。
たとえば、「InputCheker(5, "ABCDEF")」と指定した場合、 出力例はこんな感じです。
1. input(ABCDEF) =>と出力して入力待ちをし、ユーザーが「ABCDEF<ENTER>」を入力したとき、 入力開始から5秒以内ならば「OK」、5秒をこえていれば「TIME OUT」を出力します。 このとき、ユーザーがキーを押下しなければ1. を出力してから たとえ10秒たっていても「TIME OUT」にはならないので注意してください。 時間計測はあくまでユーザーが入力を開始してからです。
このお題はraynstardさんの投稿です。ご協力ありがとうございます。
[ reply ]