不要从sys.stdin中读取较早的输入

时间:2019-04-02 08:19:50

标签: python python-3.x input command-prompt

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

import sys
import click
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键,而默认设置是这样。

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

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)。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

结果是我需要termios.tcflush()termios.TCIFLUSH来完成要求的工作:

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!")