Search code examples
pythoninputtimeralarm

Problem with alarm code, need user input and timer in background. Timer works, but doesn't stop program


I'm writing code for an alarm system that runs for a predefined amount of time and allows a user to input code up to three times. If the code isn't entered correctly within 3 times I have a print statement (will eventually append this with more code) that works as defined, the problem is I need the timeout to execute some code similarly. As in, if timeout then do this as well, (essentially go to the same line of code the input failure goes to)

TIMEOUT = 7 # number of seconds your want for timeout
keycode ="0000";
count = 3

def interrupted(signum, frame):
    "called when read times out"
    print ('Input timeout!!  Contacting Owner!')
signal.signal(signal.SIGALRM, interrupted)


def input():    
 try:      
  count = 3
  for i in range(3,0,-1):

   userIn= raw_input("Enter the security code to disable the alarm 
system\n");
   if userIn != keycode :
             count = count-1;
             print ("Incorrect Password...Tries Remaining", count);



   else:
             print("Password accepted, security system offline");
             #BRANCHING CODE GOES HERE
             break

  if count == 0:
           print("Contacting Owner!");

           #BRANCHING CODE GOES HERE


 except:
     return


# set alarm
signal.alarm(TIMEOUT)
s = input()
# disable the alarm after success
signal.alarm(0)

After timeout, message prints Input timeout!! Contacting Owner!, but the user can still enter a password. This is obviously not a very good alarm system! Ideally I could create an or statement at the "if count == 0 or TIMEOUT: True" kind of thing.


Solution

  • For some reason adding this little bit of code to the definition section solved the problem

    I don't know why, and I don't know how, but getting rid of the 0 on return0 or moving it a space away breaks the codes functionality. If anyone can explain why that would be amazing.

    a = 1 ;
    def interrupted(signum, frame):
    
         a = 0;
         "called when read times out"
         print ('Input timeout!!  Contacting Owner!');
         if a == 0:
            return0
    signal.signal(signal.SIGALRM, interrupted)