direct_test_reminder.py•4.61 kB
# direct_test_reminder.py
import subprocess
import json
from datetime import datetime
def escape_quotes(text):
"""
转义字符串中的引号,以便在 AppleScript 中使用
"""
return text.replace('"', '\\"')
def create_reminder_applescript(title, notes, date, time):
"""
创建用于添加提醒事项的 AppleScript 脚本
"""
# 基本脚本 - 创建提醒事项
script = f'''
tell application "Reminders"
set newReminder to make new reminder with properties {{name:"{escape_quotes(title)}"}}
'''
# 添加备注(如果提供)
if notes:
script += f'\n set body of newReminder to "{escape_quotes(notes)}"'
# 添加提醒日期和时间(如果提供)
if date:
try:
# 解析日期
date_obj = datetime.strptime(date, "%Y-%m-%d")
# 设置日期的 AppleScript
script += f'''
-- 设置提醒日期
set dueDate to current date
set year of dueDate to {date_obj.year}
set month of dueDate to {date_obj.month}
set day of dueDate to {date_obj.day}
'''
# 如果还提供了时间,则设置时间
if time:
try:
# 解析时间
time_obj = datetime.strptime(time, "%H:%M:%S")
# 设置时间的 AppleScript
script += f'''
-- 设置提醒时间
set hours of dueDate to {time_obj.hour}
set minutes of dueDate to {time_obj.minute}
set seconds of dueDate to {time_obj.second}
'''
except ValueError:
print(f"无效的时间格式: {time},将只使用日期")
# 设置提醒日期时间
script += '''
set due date of newReminder to dueDate
'''
except ValueError:
print(f"无效的日期格式: {date},将不设置提醒日期")
# 完成脚本 - 保存提醒事项并返回 ID
script += '''
save
return id of newReminder as string
end tell
'''
return script
def run_applescript(script):
"""
执行 AppleScript 并返回结果
"""
process = subprocess.Popen(
['osascript', '-e', script],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
stdout, stderr = process.communicate()
if process.returncode != 0:
raise Exception(f"AppleScript 执行失败: {stderr}")
return stdout
def test_create_reminder():
"""
测试创建提醒事项功能
"""
# 测试用例
test_cases = [
{
"title": "测试提醒事项1",
"notes": "这是一个测试提醒事项,无日期",
"date": "",
"time": ""
},
{
"title": "测试提醒事项2",
"notes": "这是一个带日期的测试提醒事项",
"date": "2025-05-20",
"time": ""
},
{
"title": "测试提醒事项3",
"notes": "这是一个带日期和时间的测试提醒事项",
"date": "2025-05-21",
"time": "14:30:00"
}
]
print("开始测试创建提醒事项功能...")
for i, test_case in enumerate(test_cases):
print(f"\n测试用例 {i+1}: {test_case['title']}")
try:
# 构建 AppleScript 命令
script = create_reminder_applescript(
test_case['title'],
test_case['notes'],
test_case['date'],
test_case['time']
)
# 输出脚本内容以便调试
print("生成的 AppleScript:")
print("-----------------------------")
print(script)
print("-----------------------------")
print(f"执行 AppleScript...")
# 执行 AppleScript
result = run_applescript(script)
# 检查结果
if result.strip():
print(f"✅ 测试通过: {test_case['title']} 创建成功")
print(f"提醒事项 ID: {result.strip()}")
else:
print(f"❌ 测试失败: {test_case['title']} 创建失败")
except Exception as e:
print(f"❌ 测试出错: {str(e)}")
if __name__ == "__main__":
test_create_reminder()