如何在python中刷新输入流?


问题内容

我正在用Python编写一个简单的警报实用程序。

#!/usr/bin/python

import time
import subprocess
import sys

alarm1 = int(raw_input("How many minutes (alarm1)? "))

while (1):
    time.sleep(60*alarm1)
    print "Alarm1"
    sys.stdout.flush()
    doit = raw_input("Continue (Y/N)?[Y]: ")
    print "Input",doit
    if doit == 'N' or doit=='n':
        print "Exiting....."
        break

我想刷新或放弃在脚本休眠时输入的所有按键,并且仅在执行raw_input()之后接受按键。

编辑:我在Windows XP上运行此。


问题答案:

这将有助于您了解所使用的操作系统,因为这是一个非常特定于操作系统的问题。例如,由于sys.stdin没有fileno属性,因此Kylar的答案在Windows上不起作用。

我很好奇,提出了一个使用curses的解决方案,但这在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