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

夙愿已清 提交于 2021-02-10 17:35:42

问题


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

回答1:


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)


来源:https://stackoverflow.com/questions/55525716/python-input-takes-old-stdin-before-input-is-called

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