0
如何使輸入有一個while循環,但我還沒有等待答案? (Python的3.6的Windows 10)
例如:如何使用可選輸入做一段時間
b = 0
While True:
b += 1
a = input('wating',b)
if a == '1': print('Great!')
time.sleep(1)
這將打印:
1
2
3
4
# But if a write 1 then it would print
5
Great!
好吧,這只是我想要做一個例子,其實我想打一個而簡單遊戲的循環菜單(簡單,因爲它是一個shell的遊戲,沒有圖形),當你在菜單中時,每一秒(即使你沒有做任何事情)遊戲檢查你是否寫了一些東西(輸入)和(即使你在輸入中寫入或不輸入東西),檢查你的屬性(減少你的食物並增加你當前的生命值)。
對不起,我的英語和感謝閱讀。
編輯:
我發現這個計算器兩種方法,他們什麼都好?我不明白他們中的任何一個,有人可以解釋我們他們的工作以及他們之間的差異嗎? (#comments我不要讓他們)
第一:
import msvcrt
import time
import sys
class TimeoutExpired(Exception):
pass
answer = ''
def input_with_timeout(prompt, timeout, timer=time.monotonic):
sys.stdout.write(prompt)
sys.stdout.flush()
endtime = timer() + timeout
result = []
while timer() < endtime:
if msvcrt.kbhit():
result.append(msvcrt.getwche()) #XXX can it block on multibyte characters?
if result[-1] == '\n': #XXX check what Windows returns here
return ''.join(result[:-1])
time.sleep(0.04) # just to yield to other processes/threads
raise TimeoutExpired
try:
answer = input_with_timeout('hi', 4)
except TimeoutExpired:
print('Sorry, times up')
else:
print('Got %r' % answer)
二:
import sys
import time
import msvcrt
def readInput(caption, default, timeout = 2):
start_time = time.time()
sys.stdout.write('%s(%s):'%(caption, default))
sys.stdout.flush()
input = ''
while True:
if msvcrt.kbhit():
byte_arr = msvcrt.getche()
if ord(byte_arr) == 13: # enter_key
break
elif ord(byte_arr) >= 32: #space_char
input += "".join(map(chr,byte_arr))
if len(input) == 0 and (time.time() - start_time) > timeout:
print("timing out, using default value.")
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)
[在Python中有超時的鍵盤輸入]的可能重複(http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python) –