Вот рабочий код, использующий signal
и Python 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: