0

I have Test class which opens infinite reading loop in its constructor using class ReadingLoopThread(Thread) and then it has to be able to execute some other functions (such as while_loop_function function). I need to catch KeyboardInterrupt in this infinite loop inside the child thread, but all I have is an error:

Exception ignored in: <module 'threading' from '/usr/lib/python3.4/threading.py'>
Traceback (most recent call last):
  File "/usr/lib/python3.4/threading.py", line 1294, in _shutdown
    t.join()
  File "/usr/lib/python3.4/threading.py", line 1060, in join
    self._wait_for_tstate_lock()
  File "/usr/lib/python3.4/threading.py", line 1076, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
KeyboardInterrupt

My code:

from threading import Thread
from time import sleep

class ReadingLoopThread(Thread):
    def __init__(self, ):
        Thread.__init__(self)
    def run(self):
        while True:
            try:
                print('a')
                sleep(0.5)
            except KeyboardInterrupt as e:
                print('in loop: interrupt')
                raise(e)

class Test:
    def __init__(self):
        self.my_thread = ReadingLoopThread()
        self.my_thread.start()

    def while_loop_function(self, msg):
        print(msg)


if __name__ == '__main__':
    try:
        test = Test()
        test.while_loop_function('blablabla')
    except Exception as e:
        print('in main')
        print(e)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
yartem
  • 41
  • 3

0 Answers0