1

Below is a code snippet of what I am trying to achieve in python. I am trying to spawn a new thread on a target function from some other function. This new thread waits on the subprocess and exits. Now I want to kill this thread whenever a request comes in. This should also kill the corresponding subprocess that it was executing.

class ABC(object):

    def process_thread(self):
        #call a child process using subprocess.call()

    def main(self):
       t = threading.Thread(target=self.process_thread)
       t.start()

obj = ABC()
obj.main()
Abhi
  • 73
  • 1
  • 6
  • 1
    have a look at [this](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python). maybe a normal thread is not what you wnat – Lawrence Benson Aug 28 '15 at 14:11
  • 1
    +1. There is no such thing as killing a thread (not safely, at least). The thread should always exit by itself. And most of the time thread is not the answer. – epx Aug 28 '15 at 14:17

2 Answers2

1

Your actual use-case has a very simple solution: use subprocess.Popen to spawn an external process. Then, monitor and control the process from Python.

 p = suprocess.Popen(...)
 #  ... some time later
 p.kill()

would be one way to do this.

No need for threads.

deets
  • 6,285
  • 29
  • 28
0

I usually have the new thread checking a global variable or a value passed in Queue, then when it sees a indicator to close the thread run:

sys.exit()

it forces the thread to close.

Added: you would use the sys.exit() in the thread you want to close This is useful for the threading module.

The thread module has a thread.exit() call, but it looks like you're using threading.

tgikal
  • 1,667
  • 1
  • 13
  • 27