本文介绍了如何在python中刷新输入流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a simple alarm utility in 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() 后接受击键.

I want to flush or discard all the key strokes that were entered while the script was sleeping and only accept the key strokes after the raw_input() is executed.

我在 windows xp 上运行这个.

I'm running this on windows xp.

推荐答案

了解您使用的操作系统会有所帮助,因为这是一个非常针对操作系统的问题.例如,Kylar 的回答在 Windows 上不起作用,因为 sys.stdin 没有 fileno 属性.

It would help to know what operating system you're using, as this is a very operating-system-specific question. For example, Kylar's answer doesn't work on Windows because sys.stdin doesn't have a fileno attribute.

我很好奇并使用curses组合了一个解决方案,但这在Windows上也不起作用:

I was curious and threw together a solution using curses, but this won't work on Windows either:

#!/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 中根本不起作用:

ah, Windows. Then you can use the msvcrt module. Note that the code below isn't perfect, and it doesn't work in IDLE at all:

#!/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

这篇关于如何在python中刷新输入流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:57