AppleScript读取文件批量输入异常:内容一次性全部输入求助
问题描述
我有一个包含50行内容的todo-sample.txt文件,内容示例:
Optimize website images Add pagination to blog post pages Implement a responsive design for the website Improve website load speed Update website copy for SEO ...
我尝试编写AppleScript解析每行内容,输入到文本框后按下回车,以此快速测试文本输入功能。但运行脚本后,文件所有内容被一次性输入,而非逐行输入后按回车。原脚本如下:
-- Set the path to the input file set input_file to "/Users/bheng/Sites/notes/Todo/todo-sample.txt" -- Open the input file set file_handle to open for access input_file -- Display a countdown timer repeat with i from 3 to 1 by -1 say i delay 1 end repeat say "Go!" -- Set the delay time between each line set delay_time to 1 -- Read each line from the file and paste it into the current application repeat with this_line in (read file_handle using delimiter return) tell application "System Events" keystroke this_line delay delay_time key code 36 -- Press enter key delay delay_time end tell end repeat -- Close the input file close access file_handle
我原本以为只有AppleScript能实现该功能,也接受其他技术或脚本语言的解决方案。
问题原因
原脚本核心问题是换行符处理错误:
- 现代文本文件默认用LF(
\n)作为换行符,但AppleScript里的return对应CR(\r)。 - 用
read file_handle using delimiter return读取文件时,找不到匹配的分隔符,整个文件会被当成单个字符串,导致循环仅执行一次,一次性输入所有内容。
修复后的AppleScript方案
以下脚本兼容LF、CR、CR/LF三种换行符,还会过滤空行:
-- 设置输入文件路径 set input_file to "/Users/bheng/Sites/notes/Todo/todo-sample.txt" -- 读取文件全部内容 set file_content to read input_file -- 分割内容为行列表(兼容所有常见换行符) set AppleScript's text item delimiters to {"\n", "\r", "\r\n"} set line_list to text items of file_content -- 过滤空行 set filtered_lines to {} repeat with line_item in line_list if line_item is not "" then set end of filtered_lines to line_item end if end repeat set AppleScript's text item delimiters to "" -- 倒计时提示 repeat with i from 3 to 1 by -1 say i delay 1 end repeat say "Go!" -- 设置每行输入的间隔时间 set delay_time to 1 -- 逐行输入并回车 repeat with this_line in filtered_lines tell application "System Events" keystroke this_line delay delay_time key code 36 -- 按下回车键 delay delay_time end tell end repeat
Python替代方案(跨平台)
如果需要跨平台的解决方案,可以用Python的pyautogui库,操作更简洁:
- 先安装依赖:
pip install pyautogui
- 编写脚本:
import pyautogui import time # 文件路径 input_file = "/Users/bheng/Sites/notes/Todo/todo-sample.txt" # 倒计时 for i in range(3, 0, -1): print(i) time.sleep(1) print("Go!") # 读取文件并过滤空行 with open(input_file, 'r') as f: lines = [line.strip() for line in f if line.strip()] delay_time = 1 # 逐行输入并回车 for line in lines: pyautogui.typewrite(line) time.sleep(delay_time) pyautogui.press('enter') time.sleep(delay_time)
内容的提问来源于stack exchange,提问作者code-8
相关产品推荐
相关产品推荐

