Apple Script 使用和常见问题

  • 平台:Mac OS
  • 工具:脚本编辑器
  • AppleScript 帮助
  • Introduction to AppleScript Language Guide

常用语句

hello world

say "hello world"
beep 2

变量

set a to {1, 2}
# 此处报错,a不能转成字符串
say a

dialog

set message to "Dialog Message"
set temp to display dialog message buttons {"OK", "Cancel"}
set selectedTitle to button returned of temp
display dialog "You pressed the following button " & selectedTitle
Apple Script 使用和常见问题_第1张图片
dialog_1
Apple Script 使用和常见问题_第2张图片
dialog_2

清空废纸篓

tell application "Finder"
    empty trash
end tell

列表选择器

choose from list {"dawei", "libai", "lilei"} with title "名字选择器" with prompt "请选择名称" default items {"lilei"} with empty selection allowed and multiple selections allowed
Apple Script 使用和常见问题_第3张图片
自定义内容选择.png

文件选择器

# choose folder 选择文件夹
choose file of type ("txt") with prompt "选取文件"
Apple Script 使用和常见问题_第4张图片
文件选择器

AppleScript 和 shell 交互

相互调用

AppleScript 调用shell

do shell script "cd ~;ls"

shell 调用 AppleScript

# osascript -e "语句"
finder=`osascript -e "set dir to POSIX path of (choose folder with prompt \"选择一个文件夹\")"`
# 输出结果/Users/xiaoniu/Documents/XXXX/
echo $finder

/** 
    osascript <

传值

AppleScript -> shell

如果是字符串,可以直接使用 & 进行拼接。

set hostname to "www.baidu.com"

do shell script "ping -c1 " & hostname

更通用的是 quoted form of

# quoted form of
set hostname to "www.baidu.com"

do shell script "ping -c1 " & quoted form of hostname

shell -> AppleScript

path=`pwd`
osascript <
Apple Script 使用和常见问题_第5张图片
shell 调用 AppleScript

很多时候,shell 需要获取Apple Script的执行结果,获取方式如下

finder=`osascript -e "set dir to POSIX path of (choose folder with prompt \"选择一个文件夹\")"`
# 输出结果/Users/xiaoniu/Documents/XXXX/
echo $finder

路径转换

set p to "/usr/local/bin/" 
set a to POSIX file p 
   -- file "Macintosh HD:usr:local:bin:"

To translate an AppleScript path (file or directory, valid or not) into a POSIX path use POSIX path of.

set a to "Macintosh HD:usr:local:bin:" 
set p to POSIX path of a 
   -- "/usr/local/bin/"

定时执行脚本

单纯的脚本虽然功能强大,但是有时候的确不是那么方便。配合定时任务,脚本可以发挥更大的功能。




  
    Label
    com.feng.record
    ProgramArguments
    
        osascript
      ~/Documents/record.scpt
    
    StartCalendarInterval
    
      Minute
      0
      Hour
      18
    
    StandardInPath
    ~/Documents/MyAppleScript/in.log
    StandardOutPath
    ~/Documents/MyAppleScript/out.log
    StandardErrorPath
    ~/Documents/MyAppleScript/err.log
  

$ plutil -lint xxx.plist
$ launchctl load ~/Library/LaunchAgents/18.plist 

每天18:00执行脚本~/Documents/record.scpt,至于这个脚本里写什么就可以自由发挥了。

# record.scpt
# 语音 + 弹窗 提醒打卡
say "快去打卡,忘记打卡就不好了!"
display dialog "快去打卡,忘记打卡就不好了!" buttons {"了解"}

你可能感兴趣的:(Apple Script 使用和常见问题)