How can I kill a running thread when exiting from __main__

kyosohma at gmail.com kyosohma at gmail.com
Tue Apr 3 13:32:49 EDT 2007


On Apr 3, 12:21 pm, car... 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)?

If you can get the pid of the process you created, you should be able
to use the killProcName function that's included with the win32
package...if you're server is a Windows box. You should be able to use
the join() method if you don't set your thread to a Daemon.

This post talks about using the os module to kill a thread as well:

http://www.daniweb.com/techtalkforums/thread36752.html

The wxPython wiki has one of the best threading examples I've seen:
http://wiki.wxpython.org/index.cgi/LongRunningTasks

Mike




More information about the Python-list mailing list