用Mac好久了,国内关于AppleScript的资料又少又乱,苹果官方文档又实在不想看下去,于是我找了本老外写的《Basics Of AppleScript》看起来简单易懂,就在这里把自己看得懂的简单翻译一下,原书有很多截图这里就不放了。

基础命令

say,beep,tell 命令

1.注释
单行注释 -- 或者 #
--这是单行注释 #这是单行注释
多行注释 (* 这是一样多行注释 *)

2.say
say "Hello AppleScript"
say命令 顾名思义就是让Mac说些什么,执行后Mac扬声器会播放"Hello AppleScript"

3.beep
beep 执行后Mac扬声器会发出"嘟"的一声
beep 10"嘟"的10声

4.tell

tell application "Finder"
      empty the trash
      open the startup disk
end tell

这个命令告诉Finder程序 执行"empty the trash"清空废纸篓 然后打开启动盘(一般是 Macintosh HD)
tell 命令必须以 end tell 结束

保存 编译 运行

使用Mac自带的脚本编辑器 AppleScript Editor
1.保存
菜单栏-文件-存储 或者快捷键 ⌘+S
保存格式可选 Script(脚本)/Script Bundle(脚本包)/Application(应用程序)/Text(普通文本)

2.导出
菜单栏-文件-导出...
导出格式和保存一样可选 Script(脚本)/Script Bundle(脚本包)/Application(应用程序)/Text(普通文本)

3.编译
点击编辑器上方菜单栏的小锤子🔨 图标进行编译,编译会检查脚本是否有错误,如果有错误会弹出对话框提示,编译通过脚本会变色以突出显示关键字等。

4.运行
点击编辑器上方菜单栏的▷执行按钮

自动输入

在编辑器中右键 选择 Tell Blocks > Tell “Finder” 就会自动输入一下代码

tell application "Finder"
	-- insert actions here
end tell

类似的其他很多语句都可以通过右键选择的方式自动生成。

变量和运算操作

1.创建变量
set x to 5 创建变量x并赋值数字5
set y to 10.5创建变量y并赋值数字10.5
set z to x + x 将x和y相加的值赋值给z。 + 加发 -减法 *乘法 /除法

字符串和对话框

1.创建字符串
set empStr to "" 空字符串
set sapceStr to " " 包含一个空格符的字符串
set myStr to "Hello AppleScript"

2.对话框

弹出一个对话框显示“Hello AppleScript”
display dialog "Hello AppleScript"

set myStr to "Hello AppleScript"
display dialog myStr

对话框dialog 有多种样式 代码块都可以通过右键快速生成

display dialog "" buttons {"OK"} default button 1
display dialog "" buttons {"Cancel"} default button 1
display dialog "" buttons {"", ""} default button 2

还可以监听对话框按钮的点击

display dialog "" buttons {"", ""} default button 2
if the button returned of the result is "" then
	-- action for 1st button goes here
else
	-- action for 2nd button goes here
end if

3.拼接字符串
使用&拼接两个字符串

set firstStr to "Hello"
set lastStr to "AppleScript"
set myStr to firstStr  & " " & lastStr

4.字符串长度
set len to the length of "Hello AppleScript" 结果输出11

5.在字符串中使用引号要用转义字符
set myStr "this is \"AppleScript\""

6.字符串转数字 数字转字符串
set input to "15" as number 将字符串"15"转成数字15
set numToStr to 15 as string 将数字15转成字符串"15"

摘录来自: Nayan Seth. “Basics of AppleScript。” Tech Barrack Solutions LLP, 2014. Apple Books. https://books.apple.com/us/book/basics-of-applescript/id861261280

posted on 2020-12-07 21:46  付心武士  阅读(129)  评论(0编辑  收藏  举报