1
import threading    
import sys    
from time import time   

def stop():

        print "stop"
        sys.exit()
t = threading.Timer(10, stop)

volts = 22

if volts > 20:

          t.start()    
          print "Start" 

After 10 seconds it prints Stop, which is fine, but it ignores the sys.exit(). I need to do a sys.exit when the timer expires.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
Rico
  • 329
  • 3
  • 9
  • possible duplicate of [Why does sys.exit() not exit when called inside a thread in Python?](http://stackoverflow.com/questions/905189/why-does-sys-exit-not-exit-when-called-inside-a-thread-in-python) – Wooble Jun 09 '14 at 00:28

1 Answers1

1

When you run

sys.exit()

inside of a thread, it raises the SystemExit exception. When you call thread.exit(), it raises the same exception, so you are only exiting your thread, not your program.

However in the case of the code you provided, exiting your thread will cause your program to finish as well.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • Thanks Martin and Wooble. I looked at the responses in the possible duplicate question. And I tried os.kill(os.getpid(), signal.SIGINT and it does work! It puts out a very long error message before doing a sys.exit(). It repeats this over 30 times, "Unhandled exception in thread started by sys.excepthook is missing lost sys.stderr" – Rico Jun 09 '14 at 01:03
  • 1
    If you use SIGKILL instead of SIGINT you won't get the massive traceback. – tom-james-watson Aug 07 '19 at 14:30