Keven Wang
Keven Wang

Reputation: 1268

python input() takes old stdin before input() is called

Python3's input() seems to take old std input between two calls to input(). Is there a way to ignore the old input, and take new input only (after input() gets called)?

import time

a = input('type something') # type "1"
print('\ngot: %s' % a)

time.sleep(5) # type "2" before timer expires

b = input('type something more')
print('\ngot: %s' % b)

output:

$ python3 input_test.py
type something
got: 1

type something more
got: 2

Upvotes: 1

Views: 365

Answers (1)

user2248259
user2248259

Reputation: 316

You can flush the input buffer prior to the second input(), like so

import time
import sys
from termios import tcflush, TCIFLUSH

a = input('type something') # type "1"
print('\ngot: %s' % a)

time.sleep(5) # type "2" before timer expires

tcflush(sys.stdin, TCIFLUSH) # flush input stream

b = input('type something more')
print('\ngot: %s' % b)

Upvotes: 1

Related Questions