1

I have a python script that launches subprocesses using subprocess.Popen. The subprocess then launches an external command (in my case, it plays an mp3). The python script needs to be able to interrupt the subprocesses, so I used the method described here which gives the subprocess its own session ID. Unfortunately, when I close the python script now, the subprocess will continue to run.

How can I make sure a subprocess launched from a script, but given a different session ID still closes when the python script stops?

Alter
  • 3,332
  • 4
  • 31
  • 56

2 Answers2

0


Is there any way to kill a Thread in Python? and make sure you use it as thread

import threading
from subprocess import call
def thread_second():
    call(["python", "secondscript.py"])
processThread = threading.Thread(target=thread_second)  # <- note extra ','
processThread.start()

print 'the file is run in the background'
  • I'm looking into this, I'm not sure it's a great solution though in my case as the subprocess is an external command. From that post, python threads dont deal well with interrupts and therefore dont deal well with closing external commands – Alter Jul 30 '17 at 21:16
  • https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python –  Jul 30 '17 at 21:17
  • Yep, that's where I got my info from. Several of the answers just say not to use threads. The top answer says 'As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.' which I think ruins my case as I'm executing an external command. The second part of the answer is also very convoluted compared to popen's simple `.terminate()` solution – Alter Jul 30 '17 at 21:24
0

TL;DR Change the Popen params: Split up the Popen cmd (ex. "list -l" -> ["list", "-l"]) and use Shell=False

~~~

The best solution I've seen so far was just not to use shell=True as an argument for Popen, this worked because I didn't really need shell=True, I was simply using it because Popen wouldn't recognize my cmd string and I was too lazy too split it into a list of args. This caused me a lot of other problems (ex. using .terminate() becomes a lot more complicated while using shell and needs to have its session id, see here)

Simply splitting the cmd from a string to a list of args lets me use Popen.terminate() without having to give it its own session id, by not having a separate session id the process will be closed when the python script is stopped

Alter
  • 3,332
  • 4
  • 31
  • 56