0

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

1 Answer 1

3

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!")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.