Apple Script 入门

一.基本数据类型

  • Boolean(布尔型) 仅仅包含两个值: True和False
  • Number(数字型)
  • Integer(整型)
  • Real(实数,小数)
    如:1,2,1.0,1.1,3.14,-1.56
  • Text(文本型) 和 String(字符串型),类型是一致
  • Date(日期型) 如 date "2009年8月30日星期日 下午12:31:34"。此格式的具体形式由“系统偏好设置-语言与文本”的相关设置决定。
  • Constant(常量型) 如 yes, no, ask 这些常量可以是已经被AppleScript预定义的,也可以是用户定义的不可变变量。这种 类型的数据一经确定不可更改。此外可以认为所有关键字都是常量型的数据
  • List (列表型) 如:{1,2,3},{{1,2},{a,b,c},},{1,1.9, "text"}
    列表型数据由{}包裹,一个列表中可以再包含列表,形成多维列表,列表里的具体数 据可以是同类型的。
  • Record (记录型) 如:{firstName:"iDoraemon", lastName:"Nathan"} 记录就是带有名称的列表。记录中的每一项都有名称(标识符)。我们可以认为List是每个数据都是匿名的Record。Record也可以进一步包含另一个Record。
    此例中,包含两个Text型数据 "iDoraemon"和 "Nathan",它们的标识符分别是firstName和lastName。通过of关键字可以得到想要的数据:firstName of {firstName:"iDoraemon", lastName:"Nathan"} 上面这行代码返回 "iDoraemon"。
  • 确定数据类型-Class of 要确定一个数据到底是什么类型的,使用Class of语句
    class of "string" 此代码得到结果text。

二.强制数据类型转换

as 关键字

用as关键字即可实现强制类型转换。用法:数据 as 类型 请注意,强制类型转换有时会丢失精度。
--文本类型转数字类型
"1.99" as real --得到Real类型的1.99,而原来的数据是Text(因为带有引号)。
"1.99" as integer --得到Integer类型的2,精度丢失!
"1" as real --得到Real类型的1.0,自动提升精度!
--转换成List类型
"text" as list --得到{"text"}
1.99 as list --得到{1.99}
{a:1, b:2} as list --得到{1, 2},精度丢失(标识符丢失)!
--错误举例
"text2" as number 1 as record --错误!Text中包含了无法转换成数字的字符。
{1, 2} as record --错误!无法获得标识符

三.运算符

Apple Script 入门_第1张图片
运算标识符
  • 逻辑运算符
    and(逻辑与),or(逻辑或)和not(逻辑非)。 三个对参与运算的数据要求均为Boolean型,not为单目运算符。
  • & 运算符 简单来说这个是合并运算符。支持任何类型数据。
    记住“&”运算符的三个规则:
    “&”左边的数据类型为Text(文本型)时,结果为Text;存在报错可能
    “&”左边的数据类型为Record(记录型)时,结果为Record;存在报错可能
    “&”左边的数据类型为其他时,结果为List类型
Text" & 1 --结果:"Text1" (Text类型)
 1 & "Text"  --结果:{1, "Text"} (List类型)
{name:"a"} & "b"  --结果:{name:"a", «class ktxt»:"b"} (Record类型,第二个元素匿名) 
3 & {name:"a"}  --结果:{3, "a"} (List类型,且丢失标识符)
{1, 2, 3} & {4, 5, 6} --结果:{1,2,3,4,5,6} (List类型-一维的)
 {1, 2, 3} & 4 & 5 & 6  --结果:同上
 {a:1, b:2} & {c:3} --结果:{a:1, b:2, c:3} (Record类型-一维的)
--错误举例
"Text" & {name:"a"} --错误!无法将Record类型数据转为文本
 {name:"a"} & 3  --错误!无法将Integer转换为Record

注释

--行尾注释
(" ")块注释

变量赋值

tell application "Finder"
    
    set myResult to (name of folders 2 through 3 of desktop)
    
end tell

5.全局变量和局部变量

在定义变量之前,增加“Global name”(全局)或者“Local name”(局部)语句 可以强制控制变量的生存空间,其中name为变量名称。

set message to "最先定义的" -- 定义局部变量

run aNewScript --运行脚本

displayA("作为形式参数定义的") --激活事件处理器displayA,并传递参数

--脚本对象定义开始--

script aNewScript
    
    set message to "在脚本对象里定义的" --重定义局部变量 message (重载)
    
    display dialog message
    
end script

-- 事件处理器定义开始

on displayA(message) --displayA是事件处理器的名称
    
    display dialog message --显示一个包含内容message的对话框
    
end displayA

数据共享

基本数据类型的共享机制(不含Record 和 list)---值传递
Record 和list -- 值引用 (要想采用值传递,需要关键字copy)

set a to 1

set b to a

display dialog "赋值的结果: a = " & a & ";b = " & b

--值传递
set c to {1,2,3,4}
set d to c 

-- 值引用

set f to {1,2,3,4}
set h to 1  --需要提醒的是,使用copy之前必须先定义
copy f to h  --给变量h赋值为f的值(List型)
set item 1 of h to 0  --修改List h中的第一个值为0

属性
属性和变量的区别
属性和变量的根本区别在于其稳固性(Consistence)。所谓稳固性,即脚本退出后其值是否保持不变。属性在脚本退出运行后,仍然记录下它最后的值,并且下一次运行时可以 被调出。属性的另一个特点是没有全局和局部之分,所有属性都是全局的。

property countTime : 0 --请注意,这个语句不是用来赋值的,而是用来初始化一个属性的!

set countTime to countTime + 1

display dialog "这是第" & countTime & "运行本脚本"

四.流程控制语句

简单形式:tell referenceToObject to statement
复合形式:以tell referenceToObject开始,end tell结尾。中间包含命令语句。
其中:refenrenceToObject为需要控制的对象,如一个应用程序、一个窗口。 statement为命令语句,包含至少一个命令

tell front window of application "Finder" to close --这是简单形式

tell application "Finder"
    
    close front window
    
end tell

if -- else 控制语句


set mark to 80

if mark is greater than 60 and mark is less than or equal to 80 then
    
    set response to "You passed the exam"
    
else if mark is greater than 80 then
    
    set response to "Congratulations ! You're smart"
    
else
    set response to "Sorry , you  lost it"
end if

display dialog response

循环控制

--循环多少次
repeat n times
 -- do something
end repeat
--直到循环
repeat until boolean
end repeat
--当型循环
repeat while boolean
end repeat

控制循环次数

repeat with loopVariable from startValueto stopValue by stepValue
end repeat

其中stepValue可省略,省略时为默认为1;loopVariable无需事先定义。 其执行流程如下图,请注意各个变量的用途

 repeat with a from 1 to 100
    set b to a
    
end repeat

List 类型循环

repeat with loopValue is list
--do something
end repeat

在循环体中,loopVariable将依次得到item 1 of list, item 2 of list....这样的指针(指向 list中的第几项)。请特别注意是指针!如果要得到list中的具体内容,使用contents of loopVariable来获得。


set myList to {"a", "b", "c"}

repeat with i in myList
    
    display dialog (contents of i)
    set contents of i to "Oh"
    
end repeat

** Considering/Ignoring语句(用于文本比较)**
此语句可以在比较文本时,指定忽略或考虑某一属性(如大小写,空格等等)。

considering attribute1 but ignoring attribute2 --compare texts
end considering
case diacriticals hyphens numeric strings punctuation white space

上面代码含义是考虑attribute1但忽略attribute2
其中 but ignoring attribute2可以省略;
considering和ignoring位置可以互换,但是end considering也要相应改成end ignoring,
当然你可以选择最简略的方式──只输入end,让编译器自己补上considering/ignoring。 attribute应该为下面列表中的任意一个:

Apple Script 入门_第2张图片
相应的参数

set a to "1.10.1"
set b to "1.9.4"

if a is greater than b then
    display dialog "a greater than b"
    
end if

considering numeric strings
    
    
    if a is greater than b then
        display dialog "a greater than b"
        
    end if
    
end considering

四.基本用户交互

  • 1.简单对话框 和 输入框
display dialog "这是一个对话框" buttons {"好的", "不接受"} default button "好的" with title "测试标题" with icon note giving up after 5

 buttons 紧跟List型参数,指定对话框拥有的按钮名称,注意最多为三个
 default button 紧跟text型参数的某一个按钮名称,设定默认按钮
 with title 紧跟text ,指定对话框的标题(省略时无标题)
 with icon 紧跟stop/note/caution中的一个或者file类型的路径,指定显示的图标
 giving up after 紧跟number型的整数,指定在number秒后自动消失对话框。

Apple Script 入门_第3张图片
提示框
  • 2.带有输入框的对话框

display dialog "带有输入框的对话框" default answer "默认回答"

只需要添加default answer (+text)就可使 普通对话框升级为输入框。其中text可以用空文 本(直接键入两个引号);添加hidden answer true命令,可以隐藏输入文本(输入密码时 用)。此外,前面介绍的关于简单对话框的几 个参数仍然可用。

display dialog "这是一个对话框" buttons {"好的", "不接受"} default answer "" default button "好的" with title "测试标题" with icon caution giving up after 5 with hidden answer
  • 3.⚠️对话框

display alert "这是一个警告" message "警告的信息" as warning 结果如左下图。
其中: message参数指定了补充信息(在对话框中以小字显示),as warning/critical/ informational指定了对话框的重要性(表面上看起来就是图标不同)。此外可用简单对话框 中的buttons(指定按钮), give up after(自动超时消失)参数。

display alert "这是一个警告" message "这是主题信息" as critical
  • 4.列表选择对话框

choose from list {"备选一", "备选二", "备选三"}
with title "这是一个列表选择框"
with prompt "请做 出选择!"
default items {"备选二"}
with empty selection allowed and multiple selections allowed

参数说明
 直接参数 紧跟List类型参数,包含所有备选项
 title 紧跟text ,标题
 prompt  提示语
 default items 紧跟list 默认选中项目
 empty selection allowed 允许不选
 multiple selections allowed  允许多选
choose from list {"dawei", "libai", "lilei"} with title "名字选择器" with prompt "请选择名称" default items {"lilei"} with empty selection allowed and multiple selections allowed
  • 5.文件选择对话框

这个对话框很类似于一般软件的另存为对话框。要求用户指定一个将来用于保存信息
的文件,请注意,Choose file name命令并不会创建文件,它的返回值是file类型的,包含完 整路径。完整语法如下
其中prompt指定提示信息,default name指定默认名称,default location指定默认存储位置, 需要file类型的参数,三个参数均可以省略。上面这段代码执行结果如下左图
choose file name with prompt "指定提示信息" default name "默认名称" default location file "Macintosh HD:Users"

choose file name with prompt "选定指定文件" default name "默认名称" default location file "Macintosh HD:Users"

选取文件夹对话框

完整语法如下:
其中prompt和default location参数同Choose File Name;另外invisibles指定显示隐藏 文件,multiple selections allowed可以多选,showing package contents显示包内容,省略时 则不显示隐藏文件/不可多选/不显示包内容。
choose folder命令返回值为alias或者是List(由alias构成,当允许多选时)

选取文件Choose File

选取文件对话框几乎和选取文件夹对话框一样,拥有几乎相同的参数、语法和返回值
类型,只是多了一个of type可选参数(后加List,list中应包含一个或多个text,指定允许选
择的文件类型)
choose file of type {"txt"}
注意:Choose Floder所有的参数,Choose File命令也可用,这里不再列举。

choose file of type {"jpg"} with prompt "选取文件" default location file "Macintosh HD:Users"

五.错误处理

  • 1.try 错误处理
try
    display dialog "你确定在桌面上创建 \"AppleScript\" 文件夹吗?"
    tell application "Finder"
        make new folder at desktop with properties {name:"AppleScript"}
    end tell
    
on error eText number eNum
    
    if eNum = -48 then
        display dialog "发生文件错误,错误内容是
" & eText
    else if eNum = -128 then
        display dialog "您按下了取消按钮,错误内容是:
" & eText
    end if
    
end try
  • 2.时间超时
    在wait for something中最多只等待x秒,如果x秒过后,仍然没 有得到预期响应就会抛出超时错误。需要说明的是:x是可以大于120的!这样就突破了 AppleScript默认的“耐心”,有时候也是有用的。
with timeout of 3 seconds
    
    display dialog "nihao"
    
end timeout

display dialog "你确实在三秒内做出了响应"

六.文件操作

相对路径 path to命令

在Mac OS X中,有很多文件夹具有特殊地位,如用户的文档文件夹
(Documents)、系统的资源库(Library)、应用程序文件夹(Application)等等,这些文 件夹经常会被使用到,而用绝对路径来表达它们的位置显然会产生可移植性问题。 AppleScript中提供的path to命令就是用来解决这个问题的:请看下面的示例代码。
可以使用path to命令来获得的文件夹非常多,如application support、applications folder、desktop、documents folder、downloads folder、system folder等等(请参阅 AppleScript字典)。from指定了文件夹所属的域,之所以要指定域是因为类似资源库 (Library)文件夹在系统中存在不只一个(用户的、系统的、本地的等)。常用user domain(默认缺省值)、system domain和local domain。

POSIX路径和POSIX file类型
POSIX路径全称Portable Operating System Interface of Unix,是IEEE的标准之一。
POSIX路径(path)只是POSIX中一个很小的部分,该路径用斜杠(/)分隔层次──注意 不是windows的反斜杠()。它具有简明性和相对性的特点,也可以用来避免绝对路径的致 命缺陷

POSIX path of alias "Macintosh HD:System:Library:CoreServices:Finder.app:" --返回"/System/Library/CoreServices/Finder.app/"
POSIX file "/Users/Nathan/Desktop/example.txt"
--返回file "Macintosh HD:Users:Nathan:Desktop:example.txt"
  • 1.文件读取
set myfile to alias "Macintosh HD:Users:chengguangfa:Desktop:nihao.txt"
read myfile

在这里有必要提一下文件结尾(end of file),如果文件是空的,在尝试读取时,会 让AppleScript抛出文件结尾错误,因此,在读取文件之前,应该养成先确定文件长度的习 惯,AppleScript中使用get eof命令(后直接跟alias类型的参数)。

  1. 示例1 --- 创建一个新的文件夹
tell application "Finder"

make new folder at desktop

end tell

2.创建100个子文件夹

tell application "Finder"
    
    make new folder at desktop with properties {name:"test"}
    -- 循环
    repeat with a from 1 to 100
        
        make new folder at folder "test" of desktop with properties {name:a as string}
        
    end repeat
    
end tell
  1. 获取FInder 文件列表
tell application "Finder"
    
    every file of desktop
    files of desktop
    
    every folder of desktop
    
    folders of desktop
    
        name of every file of desktop
end tell

提取符合条件的文件夹

tell application "Finder"
    
    every file of desktop whose name contains "a"
    
end tell

你可能感兴趣的:(Apple Script 入门)