【问题标题】:How do I timeout waiting for `input`? [duplicate]如何超时等待“输入”? [复制]
【发布时间】:2016-07-30 05:27:48
【问题描述】:

让我们说:

import.time

print('Make a guess: ')

time.sleep(0.5)

guess = input()

if guess == 45:
   print('Correct')

我只希望在 45 的写入时间少于 4 秒的情况下它可以工作。我该怎么做?

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您可以做的最简单的事情是记录所花费的时间:

    import time
    
    start = time.time()
    guess = input()
    end = time.time()
    
    if end-start > 4:
        print('Sorry, you took too long!')
    elif guess == '45':
        print("Hooray! You're right!")
    else:
        print('Nope, sorry.')
    

    注意:我还把45改成了'45',因为input在Python3中返回一个字符串。如果您使用的是 Python2,则应改用 guess = raw_input()

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 2020-02-23
      • 2013-11-13
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 2020-03-09
      • 2021-12-04
      相关资源
      最近更新 更多