How can I kill a running thread when exiting from __main__

Steve Holden steve at holdenweb.com
Tue Apr 3 19:32:47 CEST 2007


care02 at gmail.com wrote:
> Hi!
> 
> I have the following problem: I have written a short Python server
> that creates an indefinite simulation thread that I want to kill when
> quitting (Ctrl-C) from Python. Googling around has not given me any
> hints on how to cleanly kill running threads before exiting. Any help
> is appreciated!
> 
> Carl
> 
> ### CODE EXTRACT ###
> 
> import pythoncom
> 
> class QueueThread( threading.Thread):
>     def __init__(self, command):
>         threading.Thread.__init__(self)
>         self.command = command
> 
>     def run(self):
>         pythoncom.CoInitialize()
>         try:
>             object = Dispatch('application')
>             execute = getattr(object, 'Execute')
>             execute(self.command )
>         finally:
>             object = None
>             pythoncom.CoUnitialize()
> 
> queuethread = QueueThread("queuehandler")
> queuethread.setDaemon(True)
> queuethread.start()
> 
> ## How can I kill "queuethread" when exiting (Ctrl-C)?
> 
The only way to do this is to have the thread regularly examine a 
"please quit" flag that is set from the main thread when termination is 
required.

There have been many suggestions to allow external forced termination of 
threads, but this is impossible to specify in a clean way that is both 
platform-independent and reliable, so it's not likely to happen.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Recent Ramblings       http://holdenweb.blogspot.com




More information about the Python-list mailing list