473,890 Members | 1,775 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I kill a running thread when exiting from __main__

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.Threa d):
def __init__(self, command):
threading.Threa d.__init__(self )
self.command = command

def run(self):
pythoncom.CoIni tialize()
try:
object = Dispatch('appli cation')
execute = getattr(object, 'Execute')
execute(self.co mmand )
finally:
object = None
pythoncom.CoUni tialize()

queuethread = QueueThread("qu euehandler")
queuethread.set Daemon(True)
queuethread.sta rt()

## How can I kill "queuethrea d" when exiting (Ctrl-C)?

Apr 3 '07 #1
5 10617
On Apr 3, 12:21 pm, car...@gmail.co m 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.Threa d):
def __init__(self, command):
threading.Threa d.__init__(self )
self.command = command

def run(self):
pythoncom.CoIni tialize()
try:
object = Dispatch('appli cation')
execute = getattr(object, 'Execute')
execute(self.co mmand )
finally:
object = None
pythoncom.CoUni tialize()

queuethread = QueueThread("qu euehandler")
queuethread.set Daemon(True)
queuethread.sta rt()

## How can I kill "queuethrea d" 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

Apr 3 '07 #2
ca****@gmail.co m 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.Threa d):
def __init__(self, command):
threading.Threa d.__init__(self )
self.command = command

def run(self):
pythoncom.CoIni tialize()
try:
object = Dispatch('appli cation')
execute = getattr(object, 'Execute')
execute(self.co mmand )
finally:
object = None
pythoncom.CoUni tialize()

queuethread = QueueThread("qu euehandler")
queuethread.set Daemon(True)
queuethread.sta rt()

## How can I kill "queuethrea d" 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

Apr 3 '07 #3

SteveThe only way to do this is to have the thread regularly examine a
Steve"please quit" flag that is set from the main thread when
Steveterminatio n is required.

I thought the process would terminate when only daemon threads were left.

Skip
Apr 3 '07 #4
sk**@pobox.com wrote:
SteveThe only way to do this is to have the thread regularly examine a
Steve"please quit" flag that is set from the main thread when
Steveterminatio n is required.

I thought the process would terminate when only daemon threads were left.

Skip
So it does - according to the documentation. In which case why is the OP
asking the question, since his code sets the queuethread daemonic before
starting it?

Maybe, then, the real answer is "just exit from the main thread"?

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

Apr 3 '07 #5

SteveMaybe, then, the real answer is "just exit from the main thread"?

Yes, I believe so. If that's not what's happening I would look to see if
there is another thread which wasn't marked as a daemon.

Skip
Apr 3 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
18904
by: Jerry Sievers | last post by:
Greetings Pythonists; I have limited experience with threaded apps and plenty with old style forked heavyweight multi-processing apps. Using Python 2.3.3 on a Redhat 7.x machine. Wondering if there is a simple way from a main python program to kill a running thread? I see with the 'threading' module the way daemonic threads behave when the main program finishes.
7
6870
by: martinnitram | last post by:
Dear all, in python, a thread can be created by t = threading.Thread. But i found that when the main (and the thread) program is running and user use Crtl+C/Crtl+Z to break the program abnormally, the thread is still running and needed to kill manually (by the pid). Is there had any safest way to kill/exit the thread program under python (when the thread program part is a forever loop)? Thank a lot
0
2076
by: Marco Nicosia | last post by:
Hello gang, My coworker and I are writing a Python class for the other developers within our team. This class is supposed to encapsulate several things, including daemonizing, setting up logging, and spawning a thread to host an XML-RPC server. I'm having a real problem with logging.Logger and threading.Thread. In the main thread, we set up two loggers, each with file handlers. We then spawn the xml-rpc server thread, and allow the...
6
42881
by: RickDee | last post by:
Understand that when I start a thread, a number will be generated and is able to get from GetHashCode method. But I would like to use this number when I want to kill certain thread, anybody know how ?? Thanks Regards
1
8993
by: John | last post by:
If my main UI thread starts a worker thread, who starts its own worker thread. So if i just close my app, in the closing event i can kill the thread the UI thread starts. but how can i kill the worker thread that the UI thread's worker thread started?
3
5864
by: Stewart | last post by:
Hey Group, Hoping someone can help me out. I have some code which starts up some asynchronous code using a delegate. The code is below. Basically my main code (not shown) calls ServerThreadStart.StartServer to start the server running asynchronously. This works fine. Shouldn't be any problems here. My question is how can I get my code to kill this code running asynchronously? There is a dlgtServer.Remove(Delegate, Delegate)
1
2988
by: james_w77 | last post by:
I am trying to use Peter's StoppableThread(threading.Thread). What I want to do is to start 5 child threads, then do something, then when got ^C keyboard exception, stop the child thread. For some reason (apparently strange for me :) ), the child threads can NOT be stopped. See the enclosed code for more info,
18
10255
by: =?Utf-8?B?VGhlU2lsdmVySGFtbWVy?= | last post by:
Because C# has no native SSH class, I am using SharpSSH. Sometimes, for reasons I do not know, a Connect call will totally lock up the thread and never return. I am sure it has something to do with weirdness going on with the server I am talking to. Anyhow, this locked up state happens once in a while (maybe once per day) and I can't figure out how to deal with the locked up thread. If I issue a Thread.Abort() the exception never...
1
303
by: Laszlo Nagy | last post by:
Python threads are cooperative. I think there was a discussion about this, about a year ago or so. The answer was that in CPython, the interpreter has this GIL. Python threads are always running on the same processor, but they are not "native". There are operating system functions to kill a thread but you must not use them because it can crash the interpreter. Python MUST clean up object reference counts, manage memory etc. The OS function...
0
9976
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11215
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10449
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9616
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8007
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7159
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5834
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
4258
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3266
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.