How to provide window of time for input(), let program move on if not used

▼魔方 西西 提交于 2021-01-27 19:42:36

问题


what I have is

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')

And what I want to do is make it so after every number printed there's a 3 second window for the user to input the value of r, and if the user does nothing then have the program move on. How do I do that?


回答1:


Here is a working code using signal and Python 3.6+ That should run under any Unix & Unix-like systems and will fail under 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')

Demo 1: Execution without timeout

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

Demo 2: Execution with timeout

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


来源:https://stackoverflow.com/questions/53907737/how-to-provide-window-of-time-for-input-let-program-move-on-if-not-used

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