Python multithreading interrupt input ()
Hi I am 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 display the message "Done!" ...
It currently only prints "Done!" ... after entering. Even after five seconds have elapsed, the user must enter input before the message "Done!" ... is displayed. How can I force 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)
You don't need a stream for 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 signaling module documentation: https://docs.python.org/2/library/signal.html
As NeoWang shows, you can do this with a signal. You can also do this with stream and signal. Here's a slightly more complete example that will allow you to enter multiple lines of data and exit if more than 5 seconds have passed since you entered:
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()