stdin中读取与上一个一起使用的先前

stdin中读取与上一个一起使用的先前

本文介绍了阻止从sys.stdin中读取与上一个一起使用的先前/先前的用户键盘输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您要在程序结尾处从终端询问用户一些信息.但是,在程序运行期间,用户按下了Enter键.

Say you want to ask the user something from the terminal at the end of your program.However, during the program run, the user pressed the enter key.

import sys
import time
print("Hit enter now to see this 'problem'")
time.sleep(1)
# Hit enter now while the program sleeps!
a=input("Do you want to delete something that is really bad to delete? [Y|n]")
if a.lower()!="n":
    print("\nNO! YOU DELETED IT!")

当然,删除具有默认响应的内容是愚蠢的,我不这样做.但是,令人讨厌的是,我(用户)有时会按Enter键,而默认设置是这样.

Of course, it's stupid to delete stuff with default response, and I don't do that. However, It's annoying that I, the user, sometimes hit enter and the default is what goes.

我实际上是使用单击来读取输入.因此,在单击执行之前,我需要一个预防性命令;

I'm actually using click to read the input. So I'd want a preventative command before click executes;

import sys
import click
import time
print("Hit enter now to see this 'problem'")
time.sleep(1)
# Hit enter now while the program sleeps!
# Clear stdin here somehow.
sys.stdin.flush() # <- doesn't work though
a=input("Do you want to delete something that is really bad to delete? [Y|n]")
if a.lower()!="n":
    print("\nNO! YOU DELETED IT!")

我正在使用Linux(Ubuntu 16.04和Mac OS).

I'm on Linux (Ubuntu 16.04 and Mac OS).

有什么想法吗?

推荐答案

结果是我需要 termios.tcflush() termios.TCIFLUSH 完全符合要求:

Turns out I needed termios.tcflush() and termios.TCIFLUSH which does exactly what is asked:

import sys
from termios import tcflush, TCIFLUSH
import click
import time
print("Hit enter now to see this 'problem'")
time.sleep(1)# Hit enter while it sleeps!
tcflush(sys.stdin, TCIFLUSH)
# Discards queued data on file descriptor 'stdin'.
# TCIFLUSH specifies that it's only the input queue.
# Use TCIOFLUSH if you also want to discard output queue.

a=input("Do you want to delete something that is really bad to delete? [Y|n]")
if a.lower()!="n":
    print("\nNO! YOU DELETED IT!")
else:
    print("Phew. It's not deleted!")

这篇关于阻止从sys.stdin中读取与上一个一起使用的先前/先前的用户键盘输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 13:57