How to kill a group of processes using a Python subprocess

I am trying to make the equivalent of the following use of the Python subprocess:

>cat /var/log/dmesg | festival --tts &
[1] 30875
>kill -9 -30875

Note that I'm killing a group of processes (as indicated by a negative sign adding the process ID) to kill all child processes. The festival is starting.

In Python, I have the following code in which two processes are created and connected through a pipe.

process_cat = subprocess.Popen([
    "cat",
    "/var/log/dmesg"
], stdout = subprocess.PIPE)
process_Festival = subprocess.Popen([
    "festival",
    "--tts"
], stdin = process_cat.stdout, stdout = subprocess.PIPE)

How should I kill these processes and their child processes in a way that is equivalent to the above Bash method? The following approach is insufficient because it does not kill child processes:

os.kill(process_cat.pid, signal.SIGKILL)
os.kill(process_Festival.pid, signal.SIGKILL)

Is there a more elegant way to do this, possibly using only one process?

+4
1

, cat |. :

process_Festival = subprocess.Popen(["festival", "--tts", "/var/log/dmesg"])

process_Festival.send_signal(1)

SIGHUP, SIGKILL, .


python. preexec_fn=os.setsid Popen:

process_Festival = subprocess.Popen(["festival", "--tts", "/var/log/dmesg"],preexec_fn=os.setsid)

:

pgrp = os.getpgid(process_Festival.pid)
os.killpg(pgrp, signal.SIGINT)
+11

All Articles