如何为input()提供时间窗口,如果不使用,让程序继续运行

时间:2018-12-23 22:49:09

标签: python-3.x input time

我所拥有的

import time

r = 0
while True:
    print(r)
    r += 1
    time.sleep(3)
    number = input()
    num = int(number)
    #????????????
    if num == r:
        print('yes')
    else:
        print('no')

我想做的是使它在打印每个数字后有一个3秒钟的窗口供用户输入r的值,如果用户不执行任何操作,则使程序继续运行。我该怎么办?

1 个答案:

答案 0 :(得分:2)

这是使用signalPython 3.6+的有效代码,该代码应在任何Unix & Unix-like系统下运行,并且在Windows下将失败:

import time
import signal

def handler_exception(signum, frame):
    # Raise an exception if timeout
    raise TimeoutError

def input_with_timeout(timeout=5):
    # Set the signal handler
    signal.signal(signal.SIGALRM, handler_exception)
    # Set the alarm based on timeout
    signal.alarm(timeout)
    try:
        number = input(f"You can edit your number during {timeout}s time: ")
        return int(number)
    finally:
        signal.alarm(0)

r = 1
while True:
    number = input("Enter your number: ")
    num = int(number)
    try:
        num = input_with_timeout()
    # Catch the exception
    # print a message and continue the rest of the program
    except TimeoutError:
        print('\n[Timeout!]')
    if num == r:
        print('yes')
    else:
        print('no')

演示1:无超时执行

Enter your number: 2
You can edit your number during 5s time: 1
yes
Enter your number:

演示2:执行超时

Enter your number: 2
You can edit your number during 5s time: 
[Timeout!]
no
Enter your number: