Search code examples
python-2.7loopsraw-input

How to print something every minute that the raw_input is not entered?


I was wondering if anyone could tell me if there is a way in python 2.7 to have the program print something every minute that the raw_input isn't entered. For example:

if raw_input == "stop loop":
    break

But while nothing is entered in the raw_input it reprints "enter something" every minute that passes.


Solution

  • Try the following example (create a file that contains the follwing code and run it with python command):

    from functools import wraps
    import errno
    import os
    import signal
    
    
    class TimeoutError(Exception):
        pass
    
    
    def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
        def decorator(func):
            def _handle_timeout(signum, frame):
                raise TimeoutError(error_message)
    
            def wrapper(*args, **kwargs):
                signal.signal(signal.SIGALRM, _handle_timeout)
                signal.alarm(seconds)
                try:
                    result = func(*args, **kwargs)
                finally:
                    signal.alarm(0)
                return result
    
            return wraps(func)(wrapper)
    
        return decorator
    
    
    @timeout(60)
    def print_something():
        return raw_input('Enter something: \n')
    
    
    if __name__ == "__main__":
        data = ""
        while data != "stop loop":
            try:
                data = print_something()
            except TimeoutError:
                continue
    

    My answer is based on the accepted answer for this SO question Timeout function if it takes too long to finish