AppleScript快速入门教程

基础语法
AppleScript 入门
一、这部分介绍注释,发出声音,弹窗

(1)简单入门

 <1>多行注释
(*
this is multi
comment
*)
<2>发出响声
 beep 3
(2)
	#表示使用"Daniel"(英国发音)发出声音,人员选择如下图1所示
	say "Hello,world" using "Daniel" --或用"--"也可以表示> 单行注释
图1<br>(3)弹窗
display alert "This is an alert" #弹窗示例

二、变量赋值,string和number类型,字符串连接

set varName3 to true                      #设置布尔值
set varName1 to "This is a string.And I love"   #这是字符串值变量
set varName2 to "12"                      #设置数字变量把双引号去掉即可
set x to varName2 as number                   #转换整形字符串为整形
set y to 2
set z to varName2 * y                     --乘法运算
display dialog z                      --把乘积以弹窗的方式展示,结果为24
--字符串连接展示
set myCountry to " China."
say varName1 & myCountry                  #把连接后的句子读出来

三、列表操作
(1)列表常用操作,获取列表长度,列表元素赋值

set varName to {"A1", "B2", "C3"}
set varName2 to {"D4", "F5", "G6"}
set item 1 of varName to "arun"               #赋值varName列表的"A1"(第1个)为"arun"
set item -3 of varName2 to "arunyang.com"         #赋值varName2列表的"D4"(倒数第3个)为"arunyang.com"
set anotherVarName to varName & varName2
#set anotherVarName to items 2 through 2 of varName2      #items 2 through 2 of 即取值范围(表示从2元素开始,到第2个元素结束),这里为"B2"
set randomValue to some item of anotherVarName        #获取anotherVarName列表里的随机值
set lengthOfList to length of varName             #表示varName列表的长度
say randomValue                       #说出anotherVarName列表里的随机值
say lengthOfList                      #说出varName列表的长度
return anotherVarName
#返回=> {"arun", "B2", "C3", "arunyang.com", "F5", "G6"}

补充:

set myList to {"a", "b", "c", "d", "e", "f"}
set shortList to items 2 through 5 of myList   #返回=>{"b", "c", "d", "e"}

(2)列表整形元素合并操作
>set numberVar to 2 as list
set numberVar2 to 4 as list
set numberVar3 to 5 as list
return numberVar & numberVar2 & numberVar3  #合并列表
#返回==>  {2, 4, 5}

(3)列表字符串元素合并操作

set StringVar to "String" as list
set listVar to {"Tacos"}
set StringVar2 to "arun"
return listVar & StringVar & StringVar2   #合并字符串列表
#返回=> {"Tacos", "String", "arun"}

(4)列表之间的合并

set list1 to {1}
set list2 to {2}
set list3 to list1 & list2
set list4 to {"", ""}
set reandom1 to some item of list4
#return list3               #返回=>{1, 2}
return reandom1               #返回=>""

四、获取用户输入
(1)弹窗按钮

set varName to display dialog "Choose an option" buttons {"option1", "option2"}    #如下图1
set varName1 to display dialog "Choose an option" default button "OK" #设置"OK"为默认按钮并高亮,如下图2
set buttonReturned to button returned of varName #返回=>选择的按钮,这里我选"option1"

图1
图2
(2)输入框

set varName to display dialog "Enter some text" default answer "" buttons {"button1", "button2", "button3"} default button "button3"   #弹出输入框,如下图1所示
#set varName1 to display dialog "Enter some text" default answer "Some default Input text"  #设置弹出输入框的默认输入内容
set stringReturned to text returned of varName
get stringReturned      

在这里插入图片描述
五、if条件语句

/=等同于≠

set var1 to 1
set var2 to 2
#if var1 ≠ var2 then    #等于=,不等于/=,小于<,大于>,大于等于>=,小于等于<=
#if var1 is equal to var2 then   #等于=
#if var1 is not equal to var2 then  #不等于
#if var1 is not less than var2 then  #不小于,即大于等于>=
set var3 to 3
set var4 to 4
#if var1 = var2 then #也可以改成or,后面可以接多个and或or语句
if var1 = var2 then
    display alert "Var1 is equal to var2"
else if var3 = var4 then
    display alert "var3 is equal var4!"
else
    display alert "Nothing returned true"
end if

在这里插入图片描述
六、for循环

(1)重复固定次数

repeat 3 times
    say "This is an action!"
end repeat

(2)

set condition to false
repeat until condition is true
    say "This is an action"       #触发了一次说的动作,下次condition为true了,所以不会执行了
    set condition to true         #设置condition为true,这个是结束repeat的条件
end repeat

(3)

set condition to 0
repeat until condition = 3    #condition = 3 是退出条件
    say "This is an action"    #会重复3次
    set condition to condition + 1
end repeat
#Result返回3

七、Try and catch

set condition to false
repeat until condition is true
    try
        set age to display dialog "Enter your age" default answer "Age here"
        set age to text returned of age as number
        set condition to true                           #只要输入的是number,这个代码块没有任何error,就会结束循环
    on error                                     #假如输入的是非number,就会报错,这里捕获错误,
        beep
        display alert "You must enter a number"
        set condition to false                          #设置condition为false就会进入下一个循环,直到condition为true
    end try
end repeat
display alert "Everything worked!"

八、函数和变量范围
(1)函数示例

on functionName(param1, param2)
    set var to param2 + 10
    display dialog param1 & " " & var
end functionName
functionName("A different string", 43)   #调用函数,如下图1所示

在这里插入图片描述
(2)

<1>函数内的变量为本地变量,函数外的变量为外部变量,两个变量互相隔离,都不能互相引用

<2>要想互相引用需要变成全局变量,即变量前加上global关键字

set var1 to "This is a variable!"         
#var为external variable即外部变量
on function()
    try
        set var to "Inner variable"   #var1为本地变量(local variable)
        display dialog var           #函数内不能访问外部变量var1,否则会报错"变量没有定义".如图1所示
    on error
        beep
        global var1            
    end try
end function
function()
set var to "Potato pie"
display dialog var                  #如图2所示
display dialog var1                 #如图3所示

在这里插入图片描述在这里插入图片描述
在这里插入图片描述
九、可以通过词典来找相应的方法名称,将应用直接拖到 Dock 上的脚本编辑器图标,然后就会显示扩展的词典(如下图1),在这里可以查看该应用支持的相应方法名称说明,比如Iterm2的词典如下图2所示:
在这里插入图片描述
十、使用脚本示例
(1)清空mac回收站

tell application "Finder"         #调用Finder程序
    empty the trash           #去清空回收站里面的垃圾
end tell                          #结束调用程序

(2)列出所选文件夹中所有的文件夹名称

set folderSelected to choose folder "Select a folder"
tell application "Finder"
    set listOfFolders to every folder of folderSelected
end tell
set theList to {}
repeat with aFolder in listOfFolders
    set temp to the name of aFolder
    set theList to theList & temp
end repeat

(3)用chrome浏览器打开指定网址

set myBlog to "http://www.arunyang.com"
 #告诉 Chrmoe 浏览器打开 URL
tell application "Google Chrome"
    # 新建一个 chrome 窗口
    set window1 to make new window
    tell window1
        set currTab to active tab of window1
        set URL of currTab to myBlog
    end tell
end tell

(4)ssh快速登录

-- Launch iTerm and log into multiple servers using SSH
tell application "iTerm"
    activate
    create window with default profile
    -- Read serverlist from file path below
    set Servers to paragraphs of (do shell script "/bin/cat /opt/applescript/serverlist")
    repeat with nextLine in Servers
        -- If line in file is not empty (blank line) do the rest
        if length of nextLine is greater than 0 then
            -- set server to "nextLine"
            -- set term to (current terminal)
            -- set term to (make new terminal)
            -- Open a new tab
            -- tell term
            tell current window
                create tab with default profile
                tell current session
                    write text "ssh-custom " & nextLine
                    -- sleep to prevent errors if we spawn too fast
                    do shell script "/bin/sleep 0.01"
                end tell
            end tell
        end if
    end repeat
    -- Close the first tab since we do not need it
    -- terminate the first session of the current terminal
    tell first tab of current window
        close
    end tell
end tell

(5)多屏登录

#! /usr/bin/osascript
-- List actions to perform
set Servers to paragraphs of (do shell script "/bin/cat /opt/applescript/serverlist")
-- Count number of Servers
--set num_actions to count of actions
set num_actions to count of Servers
 
-- Set cols and lines
set num_cols to round (num_actions ^ 0.5)
set num_lines to round (num_actions / num_cols) rounding up
 
-- Start iTerm
tell application "iTerm"
    activate
 
    # Create new tab
    tell current window
        create tab with default profile
    end tell
 
    -- Prepare horizontal panes
    repeat with i from 1 to num_lines
        tell session 1 of current tab of current window
            if i < num_lines then
                split horizontally with default profile
            end if
        end tell
    end repeat
 
    -- Prepare vertical panes
    set sessid to 1
    repeat with i from 1 to num_lines
        if i is not 1 then set sessid to sessid + num_cols
        if i is not num_lines or num_actions is num_cols * num_lines then
            set cols to num_cols - 1
        else
            set cols to (num_actions - ((num_lines - 1) * num_cols)) - 1
        end if
        repeat with j from 1 to (cols)
            tell session sessid of current tab of current window
                split vertically with default profile
            end tell
        end repeat
    end repeat
 
    -- Execute actions
    repeat with i from 1 to num_actions
        tell session i of current tab of current window
    set Server to item i of Servers
    if length of Server is greater than 0 then
      write text "ssh-ele " & Server
      do shell script "/bin/sleep 0.01"
    end if
        end tell
    end repeat
end tell
AppleScript 简明基础教程 iDoraemon Nathan 编著 目录 第一章 AppleScript入门! 第一节 什么是AppleScript! 第二节 AppleScript的工作机制! 第三节 AppleScript的用途和它带来的好处! 第四节 和AppleScript有关的程序和设置! 第五节 Automator和AppleScript! 第二章 快速上手AppleScript编辑器! 第一节 挖掘实用的功能! 第二节 脚本的存储格式! 第三节 支持AppleScript的应用程序! 第四节 AppleScript的录制功能! 应用实例1:建立100个子文件夹! 第三章 AppleScrip语言初步! 第一节 对象、属性和命令! 第二节 标识符和关键字! 第三节 数据类型! 第四节 强制数据类型转换! 第五节 运算符! 第六节 提取对象中的元素! 第七节 添加注释和括号! 第八节 代码缩写! 第四章 读懂AppleScript字典! 第一节 打开特定应用程序的AppleScript字典! 第二节 读懂AppleScript字典! 第五章 变量和属性! ! Nathan编著 3  第一节 变量的概念! 第二节 全局变量和局部变量! 第三节 数据共享机制! 第四节 属性! 第五节 预定义变量! 第六章 流程控制语句! 第一节 Tell语句! 第二节 条件语句If! 第三节 循环语句! 第四节 Considering/Ignoring语句(用于文本比较)! 第七章 基本用户交互! 第一节 简单对话框和输入框! 第二节 警告对话框! 第三节 列表选择对话框! 第四节 文件选择对话框! 第五节 其他用户交互! 第八章 错误处理! 第一节 基本的Try语句! 第二节 带有错误处理的Try语句! 第三节 AppleScript中的错误(Error)! 第四节 超时(Timeout)! 第九章 文件操作! 第一节 Alias类型! 第二节 相对路径和POSIX路径! 第三节 文件读取! 第四节 文件写入! Nathan编著 4 第十章 事件处理器! 第一节 基本的事件处理器! 第二节 带参数的事件处理器! 第三节 返回值! 第四节 run和open事件处理器! 第五节 保持打开的脚本应用程序! 第六节 文件夹操作! 第十一章 脚本对象! 第一节 me关键字! 第二节 编写和使用基本的script对象! 第三节 载入和调用外部script对象! 第四节 修改外部script对象中的属性变量! 附录一:AppleScript保留关键字! 附录二:预定义的错误代码和错误信息! AppleScript错误:! Mac OS系统错误! 后记!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值