Python - 执行时中断函数
Python - interrupting function while executing
我在 python 中很难找到我的问题的解决方案。我有一个使用文本到语音的功能,可以说出给定的短语。我希望能够在过程中中断该功能。例如,我的电脑正在说一个很长的段落,我想让它停止说话。我该怎么做。可能吗?
这就是我做 TTS 的方式:
os.system('say -v Oliver "' + text + '"')
此致
您可以使用 KeyboardInterrupt 异常结束 say。您需要使用 Popen [子进程的函数] 生成 say 并附加一个进程 ID,以便稍后在触发异常时终止它。
import signal
import subprocess
try:
# 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(proc.pid), signal.SIGTERM)
pass
我在 python 中很难找到我的问题的解决方案。我有一个使用文本到语音的功能,可以说出给定的短语。我希望能够在过程中中断该功能。例如,我的电脑正在说一个很长的段落,我想让它停止说话。我该怎么做。可能吗?
这就是我做 TTS 的方式:
os.system('say -v Oliver "' + text + '"')
此致
您可以使用 KeyboardInterrupt 异常结束 say。您需要使用 Popen [子进程的函数] 生成 say 并附加一个进程 ID,以便稍后在触发异常时终止它。
import signal
import subprocess
try:
# 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(proc.pid), signal.SIGTERM)
pass