macOS不原生支持AppleScript读取硬件传感器,需依赖iStats等第三方工具;iStats兼容Intel和Apple Silicon,可获取CPU温度、风扇转速、电池健康等数据,配合AppleScript调用并解析。
macos 系统本身不直接向 applescript 暴露硬件传感器(如 cpu 温度、风扇转速、电池健康、电压等)的原生接口。applescript 无法单独完成该任务,必须借助第三方命令行工具采集数据,再由 applescript 调用并解析结果。
需要依赖 smcutil 或 iStats 等命令行工具
macOS 的 SMC(System Management Controller)芯片管理着温度、风扇、电压等传感器,但 Apple 官方未开放 API。目前较可靠的方式是使用开源工具:
-
iStats:Ruby 工具,支持 Intel 和 Apple Silicon(M1/M2/M3)Mac,可读取温度、风扇、电池状态等,安装简单:
brew install istats - smcutil:轻量级 C 工具,仅支持 Intel Mac,需手动编译,读取原始 SMC 值,但需查表解码,对新手不友好
- osx-cpu-temp:专注 CPU 温度,小巧,但功能单一
AppleScript 调用 iStats 获取常用传感器数据
以下是一个可直接运行的 AppleScript 示例,用于获取 CPU 温度、风扇转速和电池当前状态:
set cpuTemp to do shell script "istats cpu temp 2>/dev/null | awk '{print $4}' | tr -d '°C'"
set fanRPM to do shell script "istats fan rpm 2>/dev/null | awk '{print $4}' | tr -d 'RPM'"
set batteryHealth to do shell script "istats battery health 2>/dev/null | awk 'NR==2 {print $3}'"
<p>display notification "CPU: " & cpuTemp & "°C, Fan: " & fanRPM & " RPM, Battery: " & batteryHealth with title "Hardware Sensors"</p>说明:
在 macOS 上通过命令行管理 Apple Calendar 事件——创建、更新、删除、搜索、导出及检查空闲时间,并提供完整的 JSON 输出供代理使用。
- 使用
2>/dev/null忽略错误(例如无风扇或 M 系列 Mac 不支持风扇读数) -
awk和tr用于提取纯数值,避免单位干扰 - M 系列 Mac 上
istats fan可能返回空或报错,建议先用istats list查看可用传感器
增强健壮性的 AppleScript 封装建议
为避免脚本崩溃,推荐封装成带错误检查的 handler:
on getSensorValue(cmd)
try
set raw to do shell script cmd
if raw is "" then return "N/A"
return text 1 thru ((offset of " " in raw) - 1) of raw
on error
return "–"
end try
end getSensorValue
<p>set cpu to getSensorValue("istats cpu temp 2>/dev/null | grep 'CPU' | awk '{print $4}' | tr -d '°C'")
set batteryTemp to getSensorValue("istats battery temp 2>/dev/null | awk '{print $4}' | tr -d '°C'")
set charge to getSensorValue("istats battery charge 2>/dev/null | awk '{print $4}' | tr -d '%'")</p><p>display alert "Sensors" message "CPU: " & cpu & "°C • Battery: " & batteryTemp & "°C (" & charge & "%)"</p>注意事项与限制
实际使用中需注意:
- Apple Silicon Mac(M系列)的传感器支持仍在完善中,部分型号可能缺少风扇或某些温度域数据
- iStats 需要定期更新以适配新系统版本,macOS 升级后若失效,请运行
brew upgrade istats - 脚本需在“系统设置 > 隐私与安全性 > 自动化”中授予终端或 Script Editor 全盘访问权限(尤其 macOS Sonoma 及更新版本)
- 不建议高频轮询(如每秒多次),SMC 访问有频率限制,过度调用可能导致短暂无响应

















