這將有助於瞭解你所使用的操作系統,因爲這是一個非常操作系統特有的問題。例如,Kylar的答案在Windows上不起作用,因爲sys.stdin沒有fileno屬性。
我很好奇,扔在一起,用詛咒的解決方案,但是這不會在Windows工作之一:
#!/usr/bin/python
import time
import sys
import curses
def alarmloop(stdscr):
stdscr.addstr("How many seconds (alarm1)? ")
curses.echo()
alarm1 = int(stdscr.getstr())
while (1):
time.sleep(alarm1)
curses.flushinp()
stdscr.clear()
stdscr.addstr("Alarm1\n")
stdscr.addstr("Continue (Y/N)?[Y]:")
doit = stdscr.getch()
stdscr.addstr("\n")
stdscr.addstr("Input "+chr(doit)+"\n")
stdscr.refresh()
if doit == ord('N') or doit == ord('n'):
stdscr.addstr("Exiting.....\n")
break
curses.wrapper(alarmloop)
編輯:啊,Windows操作系統。然後你可以使用msvcrt模塊。請注意,下面的代碼是不完美的,它不會在IDLE在所有的工作:
#!/usr/bin/python
import time
import subprocess
import sys
import msvcrt
alarm1 = int(raw_input("How many seconds (alarm1)? "))
while (1):
time.sleep(alarm1)
print "Alarm1"
sys.stdout.flush()
# Try to flush the buffer
while msvcrt.kbhit():
msvcrt.getch()
print "Continue (Y/N)?[Y]"
doit = msvcrt.getch()
print "Input",doit
if doit == 'N' or doit=='n':
print "Exiting....."
break
'sys.stdout.flush();' – 2010-03-26 04:21:39
''''''''''''''''''''''''''''''我不好,你說得對,我不需要分號。修復了代碼。 – Amjith 2010-03-26 05:20:18
「沖洗或丟棄所有擊鍵」?你的意思是「閱讀並忽略」你不能輕易地「沖洗」輸入。爲什麼不做簡單明顯的事情:閱讀並忽略它們? – 2010-03-26 10:15:44