1

How do I make a program terminate in 5 seconds or keyboard input is recognised, in this example:

vb = input("Press Enter to Close the Window\n Or wait 5 seconds and the window will close automatically\n\n")

2 Answers2

3

You can use inputimeout pakage for this purpose.

in prompt: Enter the display message

in timeout: Timeout in seconds

from inputimeout import inputimeout
....
Your exiting code
....
....
vb = inputimeout(prompt='Press Enter to Close the Window\n Or wait 5 seconds and the window will close automatically\n\n', timeout=5)
Gowdham V
  • 574
  • 3
  • 4
2

Here is a way to do it using signals:

import signal
import time

def handler(s, f):
    raise Exception("timeout")
    
signal.signal(signal.SIGALRM, handler)

signal.alarm(5)

try:
    vb = input("Press enter or wait ")
    signal.alarm(0)
except Exception as e:
    pass
klutt
  • 30,332
  • 17
  • 55
  • 95