Why sys.exit does not exit ?

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Mar 13 16:43:28 CET 2003

Gerhard Häring <gerhard.haering at opus-gmbh.net> wrote in
news:slrnb7177r.gg.gerhard.haering at haering.opus-gmbh.net: 

> Giorge <me at nospam.pls> wrote:
>> Hi all, here is a small code snippet that should
>> tell something about what I'm trying to do:
>> import sys, os, thread, time
>> from threading import *
>> [...]
>> The problem here is that the sys.exit call doesn't
>> terminate the program, which exits after the sleep
>> call.
>> Can you help ? thanks.
> sys.exit only exits the main thread. In order for the program to
> finish, you have to complete all other threads, too.

That isn't quite the problem here.

sys.exit works by raising an exception. The default exception handler for 
the main thread recognises the SystemExit exception, outputs any associated 
string then terminates the process.

If you raise the exception in another thread it gets handled by the default 
exception handler for that thread, which simply terminates that thread. If 
you handle the SystemExit exception yourself then again it won't 
necessarily cause the program to exit.

The solution here would be to make the main thread wait on a queue (or 
other IPC object), and the timer post a message to the queue. Once the main 
thread has received the message it can exit.

The related issue is that the program normally only exits when all threads 
have completed. The remedy for this is simply to mark threads that don't 
need to die as daemon threads (by calling the setDaemon method). You can't 
mark the main thread as a daemon, that one must exit.

Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list