Python multithreading interrupt input()

左心房为你撑大大i 提交于 2019-12-01 23:54:10

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

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!