Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

threading ignores KeyboardInterrupt exception

I'm running this simple code:

import threading, time  class reqthread(threading.Thread):         def run(self):         for i in range(0, 10):             time.sleep(1)             print('.')  try:     thread = reqthread()     thread.start() except (KeyboardInterrupt, SystemExit):     print('\n! Received keyboard interrupt, quitting threads.\n') 

But when I run it, it prints

$ python prova.py . . ^C. . . . . . . . Exception KeyboardInterrupt in <module 'threading' from '/usr/lib/python2.6/threading.pyc'> ignored 

In fact python thread ignore my Ctrl+C keyboard interrupt and doesn't print Received Keyboard Interrupt. Why? What is wrong with this code?

like image 734
Emilio Avatar asked Sep 24 '10 14:09

Emilio


People also ask

How do I fix KeyboardInterrupt in Python?

In Python, there is no special syntax for the KeyboardInterrupt exception; it is handled in the usual try and except block. The code that potentially causes the problem is written inside the try block, and the 'raise' keyword is used to raise the exception, or the python interpreter raises it automatically.

Does except exception catch KeyboardInterrupt?

KeyboardInterrupt exception inherits the BaseException and similar to the general exceptions in python, it is handled by try except statement in order to stop abrupt exiting of program by interpreter. As seen above, KeyboardInterrupt exception is a normal exception which is thrown to handle the keyboard related issues.

What is thread daemon in Python?

The threads which are always going to run in the background that provides supports to main or non-daemon threads, those background executing threads are considered as Daemon Threads. The Daemon Thread does not block the main thread from exiting and continues to run in the background.


1 Answers

Try

try:   thread=reqthread()   thread.daemon=True   thread.start()   while True: time.sleep(100) except (KeyboardInterrupt, SystemExit):   print '\n! Received keyboard interrupt, quitting threads.\n' 

Without the call to time.sleep, the main process is jumping out of the try...except block too early, so the KeyboardInterrupt is not caught. My first thought was to use thread.join, but that seems to block the main process (ignoring KeyboardInterrupt) until the thread is finished.

thread.daemon=True causes the thread to terminate when the main process ends.

like image 146
unutbu Avatar answered Oct 13 '22 09:10

unutbu