Skip to content

Instantly share code, notes, and snippets.

@pythoninthegrass
Created July 8, 2024 21:04
Show Gist options
  • Save pythoninthegrass/f07645e3605ce103c4d4f7c1b5c6ff42 to your computer and use it in GitHub Desktop.
Save pythoninthegrass/f07645e3605ce103c4d4f7c1b5c6ff42 to your computer and use it in GitHub Desktop.
Use python signals to enforce a user input timeout
#!/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