如何在后台运行Python子进程管道然后杀死它

问题描述 投票:0回答:1

我想让语音合成程序Festival产生声音,直到它被杀死。在 Bash 中,我想做的事情如下:

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

当我尝试使用

subprocess
执行此操作时,我的代码在使用通信功能时挂起。我该如何解决这个问题?该进程应立即终止。

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)
python subprocess pipe kill
1个回答
1
投票

process_Festival.communicate()
是阻塞调用。您应该删除它,并在
process_Festival.kill()
之后使用
raw_input
来终止进程。

© www.soinside.com 2019 - 2024. All rights reserved.