我運行在命令窗口(Windows 7,Python的3.1)的方法,其中,我想用戶通過按下退出鍵中止該過程。然而,按下ESCape鍵似乎沒有做任何事情:-(,循環不會中斷,我也嘗試從我的IDE(Wing)中運行腳本,但同樣,循環不能中斷。如何檢測Python中的ESCape按鍵?
以下是證明了概念我的測試的精簡版...
import msvcrt
import time
aborted = False
for time_remaining in range(10,0,-1):
# First of all, check if ESCape was pressed
if msvcrt.kbhit() and msvcrt.getch()==chr(27):
aborted = True
break
print(str(time_remaining)) # so I can see loop is working
time.sleep(1) # delay for 1 second
#endfor timing loop
if aborted:
print("Program was aborted")
else:
print("Program was not aborted")
time.sleep(5) # to see result in command window before it disappears!
如果有誰能夠告訴我在哪裏我可能會去錯了,我將不勝感激。
謝謝 - 所有3個解決方案都可以工作,所以現在我需要決定哪一個最適合我的編程風格;-)問候。 – 2011-02-28 20:25:20