1

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.

Right leg
  • 16,080
  • 7
  • 48
  • 81
Ryan
  • 99
  • 1
  • 12

1 Answers1

0

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

Community
  • 1
  • 1
ettanany
  • 19,038
  • 9
  • 47
  • 63
  • I am running this and it does the job but doesn't repeat if nothing is entered it only repeats once something is entered in "data" am I doing something wrong? – Ryan Nov 15 '16 at 10:26
  • It should work, did you wait for 60 seconds and nothing happened? – ettanany Nov 15 '16 at 11:37
  • Thank you very much @ettanany this works. I was just wondering if you could explain how the decorator function works and what it exactly does purely out of curiosity so I can use it if need be. – Ryan Nov 16 '16 at 07:25
  • The decorator is used to change the function behavior. You may need to take a look at some tutorial about decorators in Python, it is an important feature. – ettanany Nov 19 '16 at 18:00