如何用AppleScript循环调用keystroke输出0000-9999数字到System Preferences
AppleScript 循环读取数字并执行输入方案
以下脚本兼容你提到的两种文本存储格式,直接替换文件路径即可使用,每次输入后预留了自定义命令的插入位置。
场景1:读取每行一个数字的文本文件
-- 替换为你的数字文本文件实际路径 set numberFile to POSIX file "/Users/你的用户名/Desktop/每行一个数字.txt" as alias set numberList to paragraphs of (read numberFile) tell application "System Preferences" to activate delay 0.5 tell application "System Events" repeat with currentNum in numberList -- 输入四位数字,自动保留前导零 keystroke currentNum as string delay 0.2 -- 可根据系统响应速度调整延迟 -- 这里插入你要执行的终端命令即可,比如 do shell script "你的命令" -- 可选:输入完成后加回车,根据你的实际需求决定是否保留 -- keystroke return delay 0.3 -- 两次输入的间隔,避免系统识别混乱 end repeat end tell
场景2:读取同行空格分隔的数字的文本文件
-- 替换为你的数字文本文件实际路径 set numberFile to POSIX file "/Users/你的用户名/Desktop/空格分隔数字.txt" as alias set fileContent to read numberFile -- 按空格分割成数字列表,自动过滤多余空字符 set AppleScript's text item delimiters to " " set numberList to text items of fileContent set AppleScript's text item delimiters to "" -- 恢复默认分隔符,避免影响其他脚本逻辑 tell application "System Preferences" to activate delay 0.5 tell application "System Events" repeat with currentNum in numberList -- 过滤分割产生的空字符串 if currentNum is not equal to "" then keystroke currentNum as string delay 0.2 -- 可根据系统响应速度调整延迟 -- 这里插入你要执行的终端命令即可,比如 do shell script "你的命令" -- 可选:输入完成后加回车,根据你的实际需求决定是否保留 -- keystroke return delay 0.3 -- 两次输入的间隔,避免系统识别混乱 end if end repeat end tell
注意事项
- 首次运行前需要给「脚本编辑器」或者你运行脚本的工具授予辅助功能权限,路径是「系统设置>隐私与安全性>辅助功能」,勾选对应程序的权限,否则
keystroke命令无法执行 - 所有延迟参数都可以根据你的系统响应速度调整,避免输入过快导致漏字或者程序无响应
- 如果不需要从文件读取,也可以直接在脚本内生成0000到9999的四位数字,不需要额外准备文本文件,生成逻辑如下:
-- 直接在脚本内生成0000到9999的四位数字列表,无需读取外部文件 set numberList to {} repeat with i from 0 to 9999 set end of numberList to text -4 thru -1 of ("0000" & i as string) end repeat
内容的提问来源于stack exchange,提问作者EL71022
相关产品推荐
相关产品推荐

