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

在EC2中通过Python脚本调用带变量的AWS CLI Polly服务问题

解决Python脚本调用AWS Polly CLI时变量嵌入问题

你当前的代码存在几个关键问题:

  • 命令拼接时,--text参数与文本内容、文本内容与输出文件名之间没有空格分隔,导致CLI无法正确识别参数边界
  • 文本内容包含空格、标点等特殊字符,未用引号包裹,会被拆解成多个无效参数
  • 使用shell=True拼接字符串存在安全注入风险,也容易引发格式解析错误

方案1:修复字符串拼接(快速解决,不推荐)

给文本内容添加双引号,同时补全参数间的空格:

import subprocess
row1 = 'My husband and I have done around 100 rooms and came to Barcelona as it has a reputation for top class rooms. We did Bajo Zero based on a recommendation from an escape room enthusiast in the UK and werent disappointed. It was a very well made immersive room with some clever puzzles. We chose hard mode and it was quite challenging as a pair but we did make it out in time. ,Escapem Elements Aire Escape Room'
# 补全空格,给文本内容包裹双引号
cmd = f'aws polly synthesize-speech --output-format mp3 --engine neural --voice-id Kevin --text "{row1}" speech1.mp3'

subprocess.call(cmd, shell=True)

方案2:用subprocess列表传参(推荐,安全无格式问题)

避免字符串拼接,直接将命令拆分为列表元素,subprocess会自动处理参数转义:

import subprocess
row1 = 'My husband and I have done around 100 rooms and came to Barcelona as it has a reputation for top class rooms. We did Bajo Zero based on a recommendation from an escape room enthusiast in the UK and werent disappointed. It was a very well made immersive room with some clever puzzles. We chose hard mode and it was quite challenging as a pair but we did make it out in time. ,Escapem Elements Aire Escape Room'
cmd_list = [
    'aws',
    'polly',
    'synthesize-speech',
    '--output-format', 'mp3',
    '--engine', 'neural',
    '--voice-id', 'Kevin',
    '--text', row1,
    'speech1.mp3'
]

subprocess.call(cmd_list)  # 无需设置shell=True

方案3:直接用boto3调用Polly API(最适合Python脚本)

既然是Python环境,直接使用AWS官方SDK比调用CLI更高效、可控,还能方便处理错误:

import boto3

# 初始化Polly客户端
polly = boto3.client('polly')
row1 = 'My husband and I have done around 100 rooms and came to Barcelona as it has a reputation for top class rooms. We did Bajo Zero based on a recommendation from an escape room enthusiast in the UK and werent disappointed. It was a very well made immersive room with some clever puzzles. We chose hard mode and it was quite challenging as a pair but we did make it out in time. ,Escapem Elements Aire Escape Room'

# 调用Polly合成语音
response = polly.synthesize_speech(
    Text=row1,
    OutputFormat='mp3',
    Engine='neural',
    VoiceId='Kevin'
)

# 保存音频文件到本地
with open('speech1.mp3', 'wb') as audio_file:
    audio_file.write(response['AudioStream'].read())

注意:EC2实例需要通过IAM角色或凭证配置,拥有访问Polly服务的权限,才能正常调用接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:35:17