基于chatgpt 开发 apple 脚本

看到的一篇博客,感觉很有意思,基于该博客进行了复现,现总结如下:

苹果手机上有备忘录软件,在这里面会记录大量日常总结或者安排,假如现在有个需求,想把备忘录里的内容导出来,一个一个地复制粘贴,显然在量比较大的时候是很浪费时间的。mac 和苹果手机的备忘录是互通的,在 mac 上可以基于 applescript 进行编程,那么我们可以通过编程来批量导出。

问题来了,难道我只是突发奇想,想导出备忘录,还要学一下 applescript 语法,查 api 手册吗?那成本也有点高。所以这时,chatgpt的优势就体现出来了。

Me: Write applescript to loop through all of my Apple Notes and output their contents

ChatGPT: Sure, here’s an AppleScript that will loop through all of your Apple Notes and output their contents:

tell application "Notes"
  set allNotes to every note
   repeat with aNote in allNotes
      set noteContent to the body of aNote
     log noteContent
   end repeat
end tell

ChatGPT: This script first tells the Notes app to get all of the notes using the every note command. Then, it loops through each note and sets the noteContent variable to the body of the note using the body of command. Finally, it logs the noteContent to the console.

ChatGPT: You can run this script by opening the Script Editor app on your Mac, creating a new script, and pasting in the code. Then, click the Run button to execute the script. The output will appear in the console.

Me: Please get note title too

ChatGPT: Sure, here’s an updated version of the AppleScript that includes the note title:

tell application "Notes"
   set allNotes to every note
   repeat with aNote in allNotes
      set noteTitle to the name of aNote
       set noteContent to the body of aNote
       log "Title: " & noteTitle & return & "Content: " & noteContent
   end repeat
end tell

This script is similar to the previous one, but it also sets the noteTitle variable to the name of each note using the name of command. Then, it logs both the noteTitle and noteContent variables to the console, separated by a line break using the & return & syntax.

ChatGPT: You can run this updated script in the same way as the previous one. It will output both the title and contents of each note in your Notes app.

在 mac 的终端上跑一下这个脚本,可以得到备忘录的全部内容。

但是内容会 全部输出到终端上,用重定向也无法将输出映射到文件中(这一点有些疑惑,考虑可能是运行了子进程的缘故),所以参考原博主的 python脚本,使用subprocess 包获取了输出,然后重定向到文件中。

#coding=utf-8
import subprocess

def cmd(command):
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8')
    for line in  process.stdout:
        line = line.strip()
        print( line)

command = """
tell application "Notes"
   repeat with eachNote in every note
      set noteTitle to the name of eachNote
      set noteBody to the body of eachNote
      set output to noteTitle & "\n" & noteBody & "\n"
      log output
   end repeat
end tell
""".strip()

cmd( ["osascript", "-e", command])

要用 python3,否则 encoding 参数会报错。

subprocess 模块允许我们启动一个新进程,并连接到它们的输入/输出/错误管道,从而获取返回值。

更多推荐

基于ChatGPT 开发 apple 脚本