Prevent reading of previous / prior user keyboard input from sys.stdin, that works with Click

故事扮演 提交于 2021-02-16 15:27:13

问题


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

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

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

Any ideas?


回答1:


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


来源:https://stackoverflow.com/questions/55470005/prevent-reading-of-previous-prior-user-keyboard-input-from-sys-stdin-that-wor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!