4

Hi I am fairly new to python and I am trying to create a program that starts a thread that after five seconds will interrupt the input () function and print the message “Done!”.
Currently it only prints “Done!” after input is given. Even after five seconds has passed, the user must enter input before the message "Done!" is displayed. How can I get the thread to interrupt the input() function?

import time
import threading

def fiveSec():
    time.sleep(5)
    print('Done!')

def main():
    t = threading.Thread(target = fiveSec)
    t.daemond = True
    t.start()
    input('::>')

if __name__ == '__main__':
    main()

(Using Python version 3.4.2)

2
  • Which OS are you using? Commented Aug 16, 2015 at 4:19
  • select.poll()? Commented Aug 16, 2015 at 4:35

2 Answers 2

4

You don't need a thread to do this, use a signal instead:

import signal
def interrupted(signum, frame):
    print "Timeout!"
signal.signal(signal.SIGALRM, interrupted)
signal.alarm(5)
try:
    s = input("::>")
except:
    print "You are interrupted."
signal.alarm(0)

You can read the documentation on signal module: https://docs.python.org/2/library/signal.html

Sign up to request clarification or add additional context in comments.

1 Comment

SIGALRM does not seem to work on windows, according to the documentation. The documentation does not offer any alternatives
2

As NeoWang shows, you can do it with a signal. You can also do it with a thread and a signal. Here is a slightly more complete example that will let you enter several lines of data, and will exit if it has been more than 5 seconds since you pressed enter:

import time
import threading
import os
import signal

class FiveSec(threading.Thread):
    def restart(self):
        self.my_timer = time.time() + 5
    def run(self, *args):
        self.restart()
        while 1:
            time.sleep(0.1)
            if time.time() >= self.my_timer:
                break
        os.kill(os.getpid(), signal.SIGINT)


def main():
    try:
        t = FiveSec()
        t.daemon = True
        t.start()
        while 1:
            x = input('::> ')
            t.restart()
            print('\nYou entered %r\n' % x)
    except KeyboardInterrupt:
        print("\nDone!")

if __name__ == '__main__':
    main()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.