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

如何通过Python使用变量控制Mac音量?报错求解

解决Mac音量控制Python代码的格式化报错

你的代码报错是因为字符串格式化语法错误——直接将字符串与括号包裹的变量拼接时,Python会误判你试图调用字符串对象,从而抛出TypeError: 'str' object is not callable。以下是几种正确传入音量值的写法:

方法1:使用老式%格式化语法

在字符串和变量之间添加%符号完成格式化:

volumes = [35, 35, 30, 35, 45, 45, 45, 45, 45, 40, 45, 45, 45, 45, 55, 45, 50, 45, 50, 55]
for i, n in enumerate(frequencies):
    osascript.osascript("set volume output volume %s" % volumes[i])

方法2:使用更直观的f-string(推荐)

Python 3.6及以上版本支持f-string,写法简洁易读:

volumes = [35, 35, 30, 35, 45, 45, 45, 45, 45, 40, 45, 45, 45, 45, 55, 45, 50, 45, 50, 55]
for i, n in enumerate(frequencies):
    osascript.osascript(f"set volume output volume {volumes[i]}")

方法3:直接遍历音量列表(简化写法)

如果frequencies的长度和volumes一致,可直接遍历音量列表,省去索引操作:

volumes = [35, 35, 30, 35, 45, 45, 45, 45, 45, 40, 45, 45, 45, 45, 55, 45, 50, 45, 50, 55]
for vol in volumes:
    osascript.osascript(f"set volume output volume {vol}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:12:41