raw_input和超时

ykm*_*izu 35 python loops raw-input

我想做一个raw_input('Enter something: .').我希望它睡3秒钟,如果没有输入,则取消提示并运行其余代码.然后代码循环并raw_input再次实现.如果用户输入类似"q"的内容,我也希望它能够破解.

rbp*_*rbp 54

有一个简单的解决方案,不使用线程(至少没有明确):使用select来知道什么时候可以从stdin读取:

import sys
from select import select

timeout = 10
print "Enter something:",
rlist, _, _ = select([sys.stdin], [], [], timeout)
if rlist:
    s = sys.stdin.readline()
    print s
else:
    print "No input. Moving on..."
Run Code Online (Sandbox Code Playgroud)

编辑[0]:​​显然这在Windows上不起作用,因为select()的底层实现需要一个套接字,而sys.stdin则不需要.感谢单挑,@ Fookatchu.

  • 不错.顺便说一句,打印提示后我必须查看`sys.stdout.flush()`才能看到它 (5认同)

Pau*_*aul 13

如果您在Windows上工作,可以尝试以下操作:

import sys, time, msvcrt

def readInput( caption, default, timeout = 5):
    start_time = time.time()
    sys.stdout.write('%s(%s):'%(caption, default));
    input = ''
    while True:
        if msvcrt.kbhit():
            chr = msvcrt.getche()
            if ord(chr) == 13: # enter_key
                break
            elif ord(chr) >= 32: #space_char
                input += chr
        if len(input) == 0 and (time.time() - start_time) > timeout:
            break

    print ''  # needed to move to next line
    if len(input) > 0:
        return input
    else:
        return default

# and some examples of usage
ans = readInput('Please type a name', 'john') 
print 'The name is %s' % ans
ans = readInput('Please enter a number', 10 ) 
print 'The number is %s' % ans 
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

33379 次

最近记录:

11 年,1 月 前