Created
July 8, 2024 21:04
-
-
Save pythoninthegrass/f07645e3605ce103c4d4f7c1b5c6ff42 to your computer and use it in GitHub Desktop.
Use python signals to enforce a user input timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import signal | |
timeout = 5 # Timeout in seconds | |
def handle_timeout(signum, frame): | |
raise TimeoutError("Input timed out!") | |
def message(name="world"): | |
return f"\nHello, {name}!" | |
def main(): | |
signal.signal(signal.SIGALRM, handle_timeout) # Set the signal handler | |
if len(sys.argv) > 1: | |
name = sys.argv[1] | |
print(message(name)) | |
else: | |
try: | |
signal.alarm(timeout) # Set the alarm | |
name = input("Please enter your name: ") | |
signal.alarm(0) # Disable the alarm | |
print(message(name)) | |
except TimeoutError: | |
print(message("stranger")) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment