初始 AppleScript
首先了解一下 Apple 公司創(chuàng)造 AppleScript 的初衷嚼锄,它是用來編寫運(yùn)行于mac的腳本的堂飞。重要的是它是 mac 上操作應(yīng)用程序?yàn)閿?shù)不多的途徑之一。非常方便實(shí)現(xiàn)一些平常工作中重復(fù)工作的腳本化事扭,提升工作效率趁仙,避免重復(fù)勞動。
AppleScript 有啥用绅项?
可以用來書寫腳本直接生成腳本文件(.scpt)、App 文件比肄;
可以用來編寫 Cocoa App(也可以創(chuàng)建 Automation Action)快耿;
可以在 Alfred.app 和 Autormator.app 中使用湿硝;
可以非常方便的在 Shell 和 OC 中調(diào)用執(zhí)行;
AppleScript 編輯器
MacOS 上有自帶的腳本編輯器润努,目前支持 AppleScript 和 JavaScript。
其中有模版工程示括、模版代碼铺浇、應(yīng)用詞典等功能,極大方便了 AppleScript/JavaScript 腳本的編寫垛膝。
基礎(chǔ)語法
-
基本數(shù)據(jù)類型
AppleScript有4種最基本的數(shù)據(jù)類型:number鳍侣、string、list和record吼拥,分別對應(yīng)編程概念中的數(shù)值倚聚、字符串、數(shù)組和字典凿可。
-
number 類型
set x to 2 get x set y to 3 get y set xy to x * y set x3 to y ^ 3
-
string 類型
set strX to "Hello " set strY to "AppleScript" -- 字符串拼接 set strXY to strX & strY -- 獲取字符串長度 set lengthOfStrXY to the length of strXY -- 分割成單個字符并組成一個新的列表 set charList to every character of strXY -- 通過 AppleScript's text item delimiters 來指定分隔號惑折,然后通過 every text item of 來實(shí)現(xiàn)分割 set defaultDelimiters to AppleScript's text item delimiters set AppleScript's text item delimiters to " " set listAfterDelimiter to every text item of strXY set AppleScript's text item delimiters to defaultDelimiters -- number 與 string 類型轉(zhuǎn)換 set numberToString to 100 as string set stringToNumber to "1234" as number
-
list 類型
set firstList to { 100, 200.0, "djfif", -10 } set emptyList to {} set currentList to { 2, 3, 4, 5 } -- 列表拼接 set modifiedList to firstList & emptyList & currentList -- 獲取和更改列表中的元素 set item 2 of modifiedList to "2" get modifiedList set the third item of modifiedList to "abcde" get modifiedList -- 用列表中的隨機(jī)元素賦值 set randomX to some item of modifiedList -- 獲取最后一個元素 set lastItem to the last item of modifiedList -- 負(fù)數(shù)表示從列表尾端開始獲取元素 set aLastItem to item -2 of modifiedList -- 獲取第一個元素 set firstItem to the first item of modifiedList set longList to { 1,2,3,4,5,6,7,8,9,10 } set shortList to items 6 through 8 of longList -- 逆向獲取子列表 set reversedList to reverse of longList set listCount to the count of longList set the end of longList to 5 get longList -- 將 string 轉(zhuǎn)換為 list set string1 to "string1" set stringList to string1 as list -- 可以用&將字符串和列表連接起來,結(jié)果取決于&前面的變量 set strAndList to string1 & stringList
-
record 類型
set aRecord to { name1:100, name2:"This is a record"} set valueOfName1 to the name1 of aRecord set newRecord to { name1:name1 of aRecord } set numberOfProperties to the count of aRecord
-
-
條件/循環(huán)
set x to 500 if x > 100 then display alert "x > 100" else if x > 10 then display alert "x > 10" else display alert "x <= 10" end if set sum to 0 set i to 0 repeat 100 times set i to i + 1 set sum to sum + i end repeat get sum repeat with counter from 0 to 10 by 2 display dialog counter end repeat set counter to 0 set listToSet to {} -- 注意下這個 ≠ 符號是使用 Option+= 輸入的 repeat while counter ≠ 10 -- display dialog counter as string set listToSet to listToSet & counter set counter to counter + 2 end repeat get listToSet set counter to 0 set listToSet to {} repeat until counter = 10 -- display dialog counter as string set listToSet to listToSet & counter set counter to counter + 2 end repeat get listToSet set aList to { 1, 2, 8 } repeat with anItem in aList display dialog anItem as string end repeat
-
注釋
-- 這是單行的注釋 (* 這是多行的注釋 這是多行的注釋 *)
-
函數(shù)
on showAlert(alertStr) display alert alertStr buttons {"I know", "Cancel"} default button "I know" end showAlert showAlert("hello world")
-
換行
-- 鍵盤使用組合鍵 Option+L 輸入'?' 可以實(shí)現(xiàn)代碼折行 on showAlert(alertStr) display alert alertStr ? buttons {"I know", "Cancel"} default button "I know" end showAlert showAlert("hello world")
-
使用AppleScript中的對話框
使用彈出框有一些要注意的地方:
- 1.它可以有多個按鈕的;
- 2.它是有返回值的,返回值是你最終操作的字符串;
- 3.它是可以增加輸入框的枯跑,而且比你想的簡單多了;
set dialogString to "Input a number here" set returnedString to display dialog dialogString default answer "" get returnedString //{button returned:"好", text returned:"asdf"} set dialogString to "Input a number here" set returnedString to display dialog dialogString default answer "" set returnedNumber to the text returned of returnedString try set returnedNumber to returnedNumber as number set calNumber to returnedNumber * 100 display dialog calNumber on error the error_message number the error_number display dialog "Error:" & the error_number & " Details:" & the error_message end try beep
-
預(yù)定義變量
就是一些特殊的關(guān)鍵字惨驶,類似于其他語言中的 self、return等敛助,有固定的含義粗卜;
千萬不要用它來自定義變量。
result:記錄最近一個命令執(zhí)行的結(jié)果纳击,如果命令沒有結(jié)果续扔,那么將會得到錯誤
it:指代最近的一個 tell 對象
me:這指代段腳本。用法舉例 path to me 返回本腳本所在絕對路徑
tab:用于string焕数,一個制表位
return:用于string纱昧,一個換行
-
字符串比較:Considering/Ignoring語句
在 AppleScript 的字符串比較方式中,你可以設(shè)定比較的方式:上面 considering 和 ignoring 含義都是清晰的堡赔,一個用于加上xx特征砌些,一個用于忽略某個特征;一個特征就是一個attribute加匈。
atrribute應(yīng)該為列表中的任意一個:case 大小寫
diacriticals 字母變調(diào)符號(如e和é)
hyphens 連字符(-)
numeric strings 數(shù)字化字符串(默認(rèn)是忽略的)存璃,用于比較版本號時啟用它。
punctuation 標(biāo)點(diǎn)符號(,.?!等等,包括中文標(biāo)點(diǎn))
-
white space 空格
ignoring case if "AAA" = "aaa" then display alert "AAA equal aaa when ignoring case" end if end ignoring considering numeric strings if "10.3" > "9.3" then display alert "10.3 > 9.3" end if end considering
-
列表選擇對話框
display alert "這是一個警告" message "這是警告的內(nèi)容" as warning choose from list {"選項(xiàng)1", "選項(xiàng)2", "選項(xiàng)3"} with title "選擇框" with prompt "請選擇選項(xiàng)"
選擇框有以下參數(shù):
- 直接參數(shù) 緊跟list類型參數(shù)雕拼,包含所有備選項(xiàng)
- title 緊跟text纵东,指定對話框的標(biāo)題
- prompt 緊跟text,指定提示信息
- default items 緊跟list啥寇,指定默認(rèn)選擇的項(xiàng)目
- empty selection allowed 后緊跟true表示允許不選
- multiple selections allowed 后緊跟true表示允許多選
-
文件選擇對話框
-- 選取文件名稱Choose File Name choose file name with prompt "指定提示信息" -- 選取文件夾Choose Folder choose folder with prompt "指定提示信息" default location file "Macintosh HD:Users" with invisibles, multiple selections allowed and showing package contents -- 選取文件Choose File choose file of type {"txt"}
-
文件讀取和寫入
文件讀取用read偎球,允許直接讀热髟;
但是寫入文件之前必須先打開文件衰絮,打開文件是open for access FileName袍冷;
寫入文件用write...to語句;
最后記得關(guān)閉文件close access filePoint
set myFile to alias "Macintosh HD:Users:xiaxuqiang:Desktop:example.txt" read myFile set aFile to alias "Macintosh HD:Users:xiaxuqiang:Desktop:example.txt" set fp to open for access aFile with write permission write "AppleScript寫入文本" to fp close access fp --在桌面上創(chuàng)建一個文件,內(nèi)部包含一個txt文件,并向txt內(nèi)插入文件 on createMyTxt() tell application "Finder" make new folder at desktop with properties {name:"star"} make new file at folder "star" of desktop with properties {name:"star.txt"} end tell end createMyTxt --向txt文件內(nèi)寫入內(nèi)容 on writeTextToFile() set txtFile to alias "Macintosh HD:Users:xiaxuqiang:Desktop:star:star.txt" set fp to open for access txtFile with write permission write "你好,這是一個txt文件" to fp as ?class utf8? close access fp end writeTextToFile createMyTxt() writeTextToFile()
-
其它語法
上面的例子只是蘋果官方文檔的精簡入門版猫牡,還有語言的面相對象特征胡诗,此處不再展開。
AppleScript 中還有比較豐富的其它 Command 集合淌友,此處也不再一一列舉煌恢。
案例列舉
-
使用 mac 的郵件系統(tǒng)
--Variables set recipientName to " 小紅" set recipientAddress to "aliyunzixun@xxx.com" set theSubject to "AppleScript Automated Email" set theContent to "This email was created and sent using AppleScript!" --Mail Tell Block tell application "Mail" --Create the message set theMessage to make new outgoing message with properties {subject:theSubject, content:theContent, visible:true} --Set a recipient tell theMessage make new to recipient with properties {name:recipientName, address:recipientAddress} --Send the Message send end tell end tell
-
讓瀏覽器打開網(wǎng)頁
set urlMyBlog to "https://blog.csdn.net/sodaslay" set urlChinaSearch to "http://www.chinaso.com" set urlBiying to "https://cn.bing.com" --使用Chrome瀏覽器 tell application "Google Chrome" --新建一個chrome窗口 set window1 to make new window tell window1 --當(dāng)前標(biāo)簽頁加載必應(yīng),就是不用百度哈哈 set currTab to active tab of window1 set URL of currTab to urlBiying --打開csdn博客,搜索 make new tab with properties {URL:urlMyBlog} make new tab with properties {URL:urlChinaSearch} --將焦點(diǎn)由最后一個打開的標(biāo)簽頁還給首個標(biāo)簽頁 set active tab index of window1 to 1 end tell end tell
-
讓你的電腦說話
-- You can use any of the voices from the System Voice pop-up on the Text to Speech tab in the Speech preferences pane. -- Default Value: -- The current System Voice (set in the Speech panel in System Preferences. tell current application say "My name is LiMei. Nice to meet you. How are you?" using "Veena" say "Fine, thanks. And you?" using "Victoria" say "滾" say "我跟你說" using "Sin-Ji" end tell beep
-
調(diào)用 mac 的通知中心
crontab + AppleScript + 通知中心 可以做很多定制的提醒工具
display notification "message" with title "title" subtitle "subtitle" display notification "message" sound name "Bottle.aiff" -- 聲音文件都在 ~/Library/Sounds 和 /System/Library/Sounds 下面
-
清理廢紙簍
tell application "Finder" empty the trash beep -- 打開啟動磁盤 open the startup disk end tell
-
模擬鍵盤按鍵消息
launch application "System Events" launch application "TextMate" tell application "System Events" set frontmost of process "TextMate" to true keystroke "input string from applescript" keystroke "a" using command down keystroke "c" using command down keystroke "a" using command down key code 124 using command down keystroke " " keystroke "v" using command down end tell
其中 using command 可以使用組合,例如:key code 53 using {command down, option down}
其中的 key code 對照表如下
apple key code list: 0 0x00 ANSI_A 1 0x01 ANSI_S 2 0x02 ANSI_D 3 0x03 ANSI_F 4 0x04 ANSI_H 5 0x05 ANSI_G 6 0x06 ANSI_Z 7 0x07 ANSI_X 8 0x08 ANSI_C 9 0x09 ANSI_V 10 0x0A ISO_Section 11 0x0B ANSI_B 12 0x0C ANSI_Q 13 0x0D ANSI_W 14 0x0E ANSI_E 15 0x0F ANSI_R 16 0x10 ANSI_Y 17 0x11 ANSI_T 18 0x12 ANSI_1 19 0x13 ANSI_2 20 0x14 ANSI_3 21 0x15 ANSI_4 22 0x16 ANSI_6 23 0x17 ANSI_5 24 0x18 ANSI_Equal 25 0x19 ANSI_9 26 0x1A ANSI_7 27 0x1B ANSI_Minus 28 0x1C ANSI_8 29 0x1D ANSI_0 30 0x1E ANSI_RightBracket 31 0x1F ANSI_O 32 0x20 ANSI_U 33 0x21 ANSI_LeftBracket 34 0x22 ANSI_I 35 0x23 ANSI_P 36 0x24 Return 37 0x25 ANSI_L 38 0x26 ANSI_J 39 0x27 ANSI_Quote 40 0x28 ANSI_K 41 0x29 ANSI_Semicolon 42 0x2A ANSI_Backslash 43 0x2B ANSI_Comma 44 0x2C ANSI_Slash 45 0x2D ANSI_N 46 0x2E ANSI_M 47 0x2F ANSI_Period 48 0x30 Tab 49 0x31 Space 50 0x32 ANSI_Grave 51 0x33 Delete 53 0x35 Escape 55 0x37 Command 56 0x38 Shift 57 0x39 CapsLock 58 0x3A Option 59 0x3B Control 60 0x3C RightShift 61 0x3D RightOption 62 0x3E RightControl 63 0x3F Function 64 0x40 F17 65 0x41 ANSI_KeypadDecimal 67 0x43 ANSI_KeypadMultiply 69 0x45 ANSI_KeypadPlus 71 0x47 ANSI_KeypadClear 72 0x48 VolumeUp 73 0x49 VolumeDown 74 0x4A Mute 75 0x4B ANSI_KeypadDivide 76 0x4C ANSI_KeypadEnter 78 0x4E ANSI_KeypadMinus 79 0x4F F18 80 0x50 F19 81 0x51 ANSI_KeypadEquals 82 0x52 ANSI_Keypad0 83 0x53 ANSI_Keypad1 84 0x54 ANSI_Keypad2 85 0x55 ANSI_Keypad3 86 0x56 ANSI_Keypad4 87 0x57 ANSI_Keypad5 88 0x58 ANSI_Keypad6 89 0x59 ANSI_Keypad7 90 0x5A F20 91 0x5B ANSI_Keypad8 92 0x5C ANSI_Keypad9 93 0x5D JIS_Yen 94 0x5E JIS_Underscore 95 0x5F JIS_KeypadComma 96 0x60 F5 97 0x61 F6 98 0x62 F7 99 0x63 F3 100 0x64 F8 101 0x65 F9 102 0x66 JIS_Eisu 103 0x67 F11 104 0x68 JIS_Kana 105 0x69 F13 106 0x6A F16 107 0x6B F14 109 0x6D F10 111 0x6F F12 113 0x71 F15 114 0x72 Help 115 0x73 Home 116 0x74 PageUp 117 0x75 ForwardDelete 118 0x76 F4 119 0x77 End 120 0x78 F2 121 0x79 PageDown 122 0x7A F1 123 0x7B LeftArrow 124 0x7C RightArrow 125 0x7D DownArrow 126 0x7E UpArrow
-
切換程序前臺震庭、設(shè)置焦點(diǎn)窗口
-- 前提是當(dāng)前 iTerm app 中打開了兩個窗口瑰抵,其中有個窗口名字叫 "2. bash" 并且該窗口中第一個 tab 中含有三個 session,本腳本的作用是讓 "2. bash" 窗口中第一個 tab 中的第三個 session 變?yōu)榻裹c(diǎn)器联。 tell the application "iTerm" activate set theWindow to the first item of ? (get the windows whose name is "2. bash") if index of theWindow is not 1 then set index of theWindow to 1 set visible of theWindow to false set visible of theWindow to true end if tell theWindow set theTab to the first item of theWindow's tabs select theTab select the third session of theTab end tell end tell
-- 下面是上面的邏輯的另一種實(shí)現(xiàn) tell the application "iTerm" activate set theWindow to the first item of ? (get the windows whose name is "2. bash") if the index of theWindow is not 1 then set the index of theWindow to 2 tell application "System Events" to ? tell application process "iTerm2" to ? keystroke "`" using command down end if end tell
-
粘貼板操作
set the clipboard to "Add this sentence at the end." tell application "TextEdit" activate --make sure TextEdit is running make new paragraph at end of document 1 with data (return & (the clipboard)) end tell
上面的例子都是一些比較簡單的例子二汛,還有很多有趣的例子可以自己根據(jù)需要,查詢詞典中涉及到的 App 的 AppleScript 接口自己做實(shí)現(xiàn)拨拓。關(guān)于如何使用 App 的 AppleScript 的詞典习贫,建議閱讀Mac 的自動化 AppleScript 終極入門手冊
何時使用?
- 一些跨應(yīng)用的重復(fù)操作步驟使用 AppleScript/JavaScript 實(shí)現(xiàn)關(guān)鍵步驟
- 結(jié)合 Alread.app千元、Automator.app苫昌、crontab 等實(shí)現(xiàn)一些場景的觸發(fā)調(diào)用
- 本地的一些工具腳本可以直接調(diào)用 AppleScript 做一些簡單的輸入、彈框幸海、通知交互
- 用 AppleScript 寫一個 CocoaApp 或者 Automator Action(但是可以用 Objective-C 我們就沒必要使用相對不熟悉的 AppleScript)
- OC 的命令行工程可以借助 NSAppleScript 操作其它應(yīng)用
- CocoaApp 工程可以通過 XPCService+ScriptingBridge+AppleScript(OC版本接口調(diào)用)啟動其它應(yīng)用(樣例工程)
生成 Cocoa App 的 OC 接口文件
需要通過 OC 調(diào)用系統(tǒng)中某個 App 的接口祟身,可以參照如下命令行導(dǎo)出其 .h 文件
sdef /Applications/Mail.app | sdp -fh -o ~/Desktop --basename Mail --bundleid `defaults read "/Applications/Mail.app/Contents/Info" CFBundleIdentifier`
更多資料
AppleScript Language Guide 官方文檔
Mac Automation Scripting Guide
AppleScript 與 Shell 的互相調(diào)用
Objective-C 運(yùn)行 AppleScript 腳本
AppleScript for Absolute Starters