0

Trying to get the program to close if an input isn't inputted in time.

from threading import Timer
import sys

loop = False
while(not loop):
timeout = 5
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
prompt = input("Enter Y or No: \n").lower()

if prompt != None:
    t.cancel()
    if (prompt == "y") or (prompt == "n"):
        print("Correct Answer")
        loop = True
        sys.exit()

Currently, once it prints Sorry, times up the input & IF sections still run.

  • Does this answer your question? https://stackoverflow.com/questions/15528939/time-limited-input – David Lukas Feb 22 '22 at 17:13
  • Still new to coding & honestly don't really understand what the person is talking about –  Feb 22 '22 at 17:17
  • Used the first part of that answer to get what I made, but doesn't end the program after printing `Sorry, times up` –  Feb 22 '22 at 17:18
  • We don't understand your code because it is not indented properly. – martineau Feb 22 '22 at 18:17

1 Answers1

0

The prompt command is waiting for input from the user.
Important likns:
Time-Limited Input?
timer objects (python) with arguments
Why does sys.exit() not exit when called inside a thread in Python?
The timeIsUp function is called after timeout seconds if t.close() is not called.

from threading import Timer
import sys,os

def timeIsUp():
  print("Sorry, times up")
  #os.kill(os.getpid(), signal.SIGINT)
  os._exit(1)

loop = False
while(not loop):
 timeout = 5
 t = Timer(timeout, timeIsUp)
 t.start()
 prompt = input("Enter Y or No: \n").lower()

 if prompt != None:
    t.cancel()
    if (prompt == "y") or (prompt == "n"):
        print("Correct Answer")
        loop = True
        sys.exit()
David Lukas
  • 1,184
  • 2
  • 8
  • 21