zeurosis
zeurosis

Reputation: 183

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

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?

Upvotes: 2

Views: 89

Answers (1)

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

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: 

Upvotes: 2

Related Questions