You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用say命令报错:'say'不是内部或外部命令问题求助

解决say命令不存在的语音播报问题

say是macOS系统专属的内置语音播报命令,Windows或Linux系统没有这个命令,所以执行代码会提示命令不存在。

解决方案

1. 针对Windows系统

Windows没有say命令,可以通过PowerShell调用系统内置的语音合成功能,修改代码如下:

import os
import platform

def say(text):
    if platform.system() == 'Windows':
        # 转义单引号避免命令执行错误
        escaped_text = text.replace("'", "\\'")
        os.system(f'powershell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(\'{escaped_text}\')"')
    elif platform.system() == 'Darwin':
        os.system(f"say {text}")

if __name__ == '__main__':
    print('PyCharm')
    say("Hello I am Jarvis A.I")

2. 使用跨平台Python库(推荐)

pyttsx3库可实现跨平台语音播报,无需依赖系统命令,兼容性更强:

  • 先安装库:
pip install pyttsx3
  • 修改代码:
import pyttsx3

def say(text):
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()

if __name__ == '__main__':
    print('PyCharm')
    say("Hello I am Jarvis A.I")

3. 针对Linux系统

Linux可安装espeak或festival等语音工具,以espeak为例:

  • 安装工具:
# Debian/Ubuntu系
sudo apt-get install espeak
# CentOS/RHEL系
sudo yum install espeak
  • 修改代码:
import os
import platform

def say(text):
    if platform.system() == 'Linux':
        os.system(f"espeak '{text}'")
    elif platform.system() == 'Darwin':
        os.system(f"say {text}")
    elif platform.system() == 'Windows':
        escaped_text = text.replace("'", "\\'")
        os.system(f'powershell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(\'{escaped_text}\')"')

if __name__ == '__main__':
    print('PyCharm')
    say("Hello I am Jarvis A.I")

内容的提问来源于stack exchange,提问作者Saureet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:27:13