The following script demonstrates how an operation which may run forever is protected by a time-out handler.
#!/usr/bin/env python import signal, sys, time # # an exception that is raised by handlerALRM # class TMO( Exception): def __init__( self, *argin): self.value = argin def __str__( self): return repr( self.value) def handlerALRM( signum, frame): print( "handlerALRM: called with ", signum) raise TMO( "tmo-exception") def main(): # # connect SIGARLM to handlerALRM # signal.signal( signal.SIGALRM, handlerALRM) # # produce a SIGALRM after 1s. # signal.alarm(1) try: # # in a realistic example time.sleep() is replaced by # code that may run into a time-out # time.sleep(3) except TMO as e: print( "Caught", e) signal.alarm(0) if __name__ == '__main__': main()