pythonsubprocesspipekill

how to run Python subprocess pipe in the background and then kill it


I want to get the speech synthesis program Festival to generate sound until it is killed. In Bash, what I'm trying to do would be something like the following:

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

When I try to do this using subprocess, my code hangs at the use of the communicate function. How can I address this? The process should be killed immediately.

raw_input(
    "Ready to set Festival running...\n" +\
    "Press Enter to continue."
)
process_cat = subprocess.Popen([
    "cat",
    "/var/log/dmesg"
], stdout = subprocess.PIPE)
process_Festival = subprocess.Popen([
    "festival",
    "--tts"
], stdin = process_cat.stdout, stdout = subprocess.PIPE)
process_Festival.communicate()[0]
raw_input(
    "Ready to stop Festival running...\n" +\
    "Press Enter to continue."
)
os.kill(process_cat.pid, signal.SIGKILL)
os.kill(process_Festival.pid, signal.SIGKILL)

Solution

  • process_Festival.communicate() is a blocking call. You should remove it and instead kill the process using process_Festival.kill() after raw_input.