30 lines
674 B
Python
30 lines
674 B
Python
"""Useful functions."""
|
|
import logging
|
|
import signal
|
|
|
|
|
|
def timed_input(message: str = None,
|
|
timeout: int = 5):
|
|
|
|
class TimeoutExpired(Exception):
|
|
pass
|
|
|
|
def interrupted(signal_number, stack_frame):
|
|
"""Called when read times out."""
|
|
raise TimeoutExpired
|
|
|
|
if message is None:
|
|
message = f"Enter something within {timeout} seconds"
|
|
|
|
signal.alarm(timeout)
|
|
signal.signal(signal.SIGALRM, interrupted)
|
|
try:
|
|
given_input = input(message)
|
|
except TimeoutExpired:
|
|
given_input = None
|
|
print() # Print end of line
|
|
logging.info("Timeout!")
|
|
signal.alarm(0)
|
|
return given_input
|
|
|