N. Chalifour N. Chalifour - 1 year ago 170
Python Question

Python - interrupting function while executing

I am having some difficulty finding a solution to my problem in python. I have a function that uses text to speech, to say the given phrase. I want to be able to interrupt the function in mid process. For example, my computer is saying a very long paragraph and I want it to stop talking. How would I do this. Is it possible?

This is how I am doing the TTS:

os.system('say -v Oliver "' + text + '"')


Answer Source

You can use the KeyboardInterrupt exception to end the say. You need to spawn the say using Popen [function of subprocess] and attach a process ID so you can later kill it if the exception is triggered.

import signal
import subprocess

    # spawn process
    proc = subprocess.Popen(["say", "-v Oliver \"{}\"".format(text)], 
            stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
    # Terminal output incase you need it
    (out, err) = proc.communicate()
except KeyboardInterrupt:
    # function to kill the subprocess
    os.killpg(os.getpgid(pro.pid), signal.SIGTERM)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download