Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multithreading interrupt input()

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)

like image 999
going gone Avatar asked Oct 16 '25 16:10

going gone


1 Answers

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

like image 56
NeoWang Avatar answered Oct 18 '25 11:10

NeoWang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!