Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 933
d3pd Avatar asked Nov 21 '25 15:11

d3pd


1 Answers

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

like image 160
Jashandeep Sohi Avatar answered Nov 23 '25 05:11

Jashandeep Sohi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!