Python sleep function does not capture interrupt signal

I can not catch the INT signal in the main thread, please tell me how to fix this problem. I want CTRL + C to interrupt the sleep method, but it waits until the timer expires.

import pygtk pygtk.require('2.0') import gtk import time import urllib2 import re import signal import sys import __main__ from time import ctime, strftime, localtime from threading import Thread myThread = None class MyThread(Thread): def __init__(self, filename): Thread.__init__(self) self.filename = filename; self.terminate = False def StopProcess(self): self.terminate = True def run(self): while self.terminate <> True: time.sleep(5) self.terminate = True def SignalHandler(signum, frame): if (myThread <> None): myThread.StopProcess() sys.exit() if __name__ == "__main__": signal.signal(signal.SIGINT, SignalHandler) myThread = MyThread("aaa") myThread.start() 
+4
source share
2 answers

Believe it or not, it will work.

 from Queue import Queue, Empty def signal_safe_sleep(delay): q = Queue() try: q.get(True, delay) except Empty: pass 

Alternatively, you can create some file descriptors using os.pipe () and then use select.select () for them in your signal_safe_sleep function. Both approaches allow you to call Python signal handlers before returning the signal_safe_sleep signal.

+2
source

Signals are transmitted only to one stream. Either only the first thread, or the first available thread, depending on the operating system.

You will have to implement your own logic to turn off other threads or make them daemon threads so that they do not interfere with the exit process.

+3
source

All Articles