如何在Python中清空标准输入流

4

我想知道在输入某些键后是否可以清除标准输入(stdin)。 我正在按照这个论坛的回复进行输入超时,类似于以下内容:

 while True:
    web_scrapping()    
    print ("Press ENTER: \n")
    time.sleep(interval)
    i, o, e = select.select( [sys.stdin], [], [], 10 )
    if (i):
        Start()

如果工作正常,请检查是否按下了某个按键,如果是,则转到Start()函数。但我的问题是Start()还有一个输入问题,因此之前的While True中的按键也会传递到Start()中,结果是Start()中的输入问题显示两次,因为之前的按键。所以我想在转到Start()之前清除那个按键。这可能吗?谢谢

调用一次raw_input来清除缓冲区怎么样?这样不够好吗? - Uriya Harpeness
Uriya,那个解决方法对我没用。 - macbeto
1个回答

2
我认为如果你正在使用UNIX系统,你应该能够在调用input之前使用termios来清除stdin中的任何排队数据。尝试像这样做:
from termios import tcflush, TCIFLUSH

while True:
    web_scraping()
    print ("Press ENTER: \n")
    time.sleep(interval)
    i, o, e = select.select( [sys.stdin], [], [], 10 )
    if (i):
        # Clear queue before asking for new input
        tcflush(sys.stdin, TCIFLUSH)
        Start()

这样做可以在调用Start时获得新的队列。注释下面例子中的第13行将会调用input,并提交调用时间队列中找到的任何内容。在调用之前清空队列有助于避免这种情况:

import select
import sys
import time
from termios import TCIFLUSH, tcflush

while True:
    print("Pretend I'm doing some stuff")
    time.sleep(2)
    i, o, e = select.select([sys.stdin], [], [], 2)
    # Enters if anything has been submitted
    if i:
        # Clear queue before asking for new input
        #   commenting it will submit whathever data is queued to stdin
        tcflush(sys.stdin, TCIFLUSH)
        a = input("Echo: ")
        print(f"your input is: {a}")
        break
    else:
        print("Nothing found in stdin")


谢谢anddt,TCIFLUSH对我有用。正是我需要的。非常感谢你的帮助。 - macbeto
太棒了,这个方法很有效。我要注意一下,与其调用 termios.tcflush(sys.stdin, termios.TCIFLUSH),我调用了 termios.tcflush(sys.stdin.fileno(), termios.TCIFLUSH),以便给它原始的文件描述符,因为其他 termios 函数似乎需要它。 - AwesomeCronk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接