【问题标题】:python input() takes old stdin before input() is calledpython input() 在调用 input() 之前采用旧的标准输入
【发布时间】:2019-04-04 22:17:28
【问题描述】:

Python3 的input() 似乎在两次调用input() 之间采用旧的标准输入。有没有办法忽略旧输入,只接受新输入(在调用input() 之后)?

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)

输出:

$ python3 input_test.py
type something
got: 1

type something more
got: 2

【问题讨论】:

    标签: python python-3.x input io stdin


    【解决方案1】:

    您可以在第二个input() 之前刷新输入缓冲区,就像这样

    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)
    

    【讨论】:

      猜你喜欢
      • 2016-05-07
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2014-12-28
      相关资源
      最近更新 更多