Linux:Python:Clear Input Buffer Before Raw_Input()

Linux : python : clear input buffer before raw_input()

For unix you can use termios.tcflush

from termios import tcflush, TCIFLUSH
import time,sys

a = raw_input("first input ")
b = raw_input("second input ")

time.sleep(5)
tcflush(sys.stdin, TCIFLUSH)

a = raw_input("third input ")
b = raw_input("fourth input ")

~$ python foo.py
first input 1
second input 2
33
33
third input 3
fourth input 4

termios.tcflush(fd, queue)

Discard queued data on file descriptor fd. The queue selector specifies which queue: TCIFLUSH for the input queue, TCOFLUSH for the output queue, or TCIOFLUSH for both queues.

How to flush the input stream?

It would help to know what operating system you're using, as this is a very operating-system-specific question. For example, Kylar's answer doesn't work on Windows because sys.stdin doesn't have a fileno attribute.

I was curious and threw together a solution using curses, but this won't work on Windows either:

#!/usr/bin/python                                                               

import time
import sys
import curses

def alarmloop(stdscr):
stdscr.addstr("How many seconds (alarm1)? ")
curses.echo()
alarm1 = int(stdscr.getstr())
while (1):
time.sleep(alarm1)
curses.flushinp()
stdscr.clear()
stdscr.addstr("Alarm1\n")
stdscr.addstr("Continue (Y/N)?[Y]:")
doit = stdscr.getch()
stdscr.addstr("\n")
stdscr.addstr("Input "+chr(doit)+"\n")
stdscr.refresh()
if doit == ord('N') or doit == ord('n'):
stdscr.addstr("Exiting.....\n")
break

curses.wrapper(alarmloop)

EDIT: ah, Windows. Then you can use the msvcrt module. Note that the code below isn't perfect, and it doesn't work in IDLE at all:

#!/usr/bin/python

import time
import subprocess
import sys
import msvcrt

alarm1 = int(raw_input("How many seconds (alarm1)? "))

while (1):
time.sleep(alarm1)
print "Alarm1"
sys.stdout.flush()

# Try to flush the buffer
while msvcrt.kbhit():
msvcrt.getch()

print "Continue (Y/N)?[Y]"
doit = msvcrt.getch()
print "Input",doit
if doit == 'N' or doit=='n':
print "Exiting....."
break

How clear stdin in Python

This is a good one, I believe that if you're working on a UNIX system you should be able to clear any queued data in stdin before calling input using termios. Try something like this:

from termios import tcflush, TCIFLUSH

while True:
web_scrapping()
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()

This should make possible to have a fresh queue when calling Start. Commenting line 13 from the example below will call input submitting whatever is found in the queue at call time. Flushing the queue before the call helps to avoid that behavior:

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

Python: flush a buffer before program termination via a finalizer

If you don't need your object to be alive at the time you perform the flush, you could use weak references

This is similar to your proposed solution, but rather than using a real reference, store a list of weak references, with a callback function to perform the flush. This way, the references aren't going to keep those objects alive, and you won't run into any circular garbage problems with __del__ methods.

You can run through the list of weak references on termination to manually flush any still alive if this needs to be guaranteed done at a certain point.

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

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

Python raw_input following sys.stdin.read() throws EOFError

Have you tried this:

message = sys.stdin.read()
sys.stdin = open('/dev/tty')
selected_index = raw_input('Which URL to open?')

This works on Linux; maybe it will work for OSX too.



Related Topics



Leave a reply



Submit