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

升级macOS Monterey后Python中调用的AppleScript脚本失效问题求助

修复macOS Monterey下AppleScript自动化失效的问题

我之前升级到Monterey后也碰到过几乎一模一样的问题,核心原因是系统对自动化权限的大幅收紧,再加上UI响应逻辑的小变化导致原有脚本失效。给你几个经过验证的修复方案:

1. 优先补全自动化权限(最关键)

Monterey的隐私控制比之前严格很多,你的Python运行环境(终端、IDE甚至虚拟环境里的Python进程)需要明确获得权限:

  • 打开「系统偏好设置」→「安全性与隐私」→「隐私」标签
  • 选择「辅助功能」,点击加号把运行脚本的程序(比如Terminal、PyCharm,或者虚拟环境下的Python可执行文件)添加进去并勾选权限
  • 同样在「完全磁盘访问权限」里也添加对应的程序,因为脚本涉及到访问本地文件路径
  • 权限添加完成后重启你的运行程序,不然权限可能不会立即生效

2. 优化原有AppleScript的稳定性

原来的脚本依赖固定延迟,Monterey的UI响应速度可能有波动,而且语法细节也需要调整,修改后的脚本如下:

import applescript

script = '''
tell application "System Events"
    -- 先激活目标应用(这里以Finder为例,可替换成你要操作的APP)
    tell application "Finder" to activate
    delay 0.5
    -- 触发Go to Folder快捷键
    keystroke "G" using {command down, shift down}
    -- 等待窗口出现,比固定延迟更可靠
    repeat until exists window "Go to Folder"
        delay 0.2
    end repeat
    -- 输入文件路径(替换成你的真实用户名)
    keystroke "/Users/your-actual-username/Documents/web_images/image_1.jpg"
    delay 0.3
    keystroke return
    delay 0.3
    keystroke return
end tell
'''

applescript.run(script)

优化要点:

  • 增加窗口存在检测循环,避免固定延迟导致的操作时机错误
  • 明确激活目标应用,确保键盘事件发送到正确的窗口
  • 缩短不必要的长延迟,平衡效率与稳定性

3. 改用系统原生osascript调用(绕过第三方库权限问题)

有时候第三方applescript库在权限传递上会有兼容性问题,直接用Python的subprocess调用系统原生命令会更稳定:

import subprocess

auto_script = '''
tell application "System Events"
    tell application "Finder" to activate
    delay 0.5
    keystroke "G" using {command down, shift down}
    repeat until exists window "Go to Folder"
        delay 0.2
    end repeat
    keystroke "/Users/your-actual-username/Documents/web_images/image_1.jpg"
    delay 0.3
    keystroke return
    delay 0.3
    keystroke return
end tell
'''

try:
    subprocess.run(['osascript', '-e', auto_script], check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as e:
    print(f"执行出错: {e.stderr}")

额外注意事项

  • 务必把脚本里的your-actual-username替换成你真实的Mac用户名
  • 如果是在特定应用的文件选择窗口执行操作,把tell application "Finder" to activate替换成对应的应用名称(比如tell application "Safari" to activate)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 03:02:44