raw_input和超時我想做一個raw_input('Enter something: .')。我希望它睡3秒鐘,如果沒有輸入,則取消提示并運行其余代碼。然后代碼循環并raw_input再次實現。如果用戶輸入類似“q”的內容,我也希望它能夠破解。
3 回答

素胚勾勒不出你
TA貢獻1827條經驗 獲得超9個贊
如果您在Windows上工作,可以嘗試以下操作:
import sys, time, msvcrtdef 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 usageans = 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
添加回答
舉報
0/150
提交
取消