Monday, August 13, 2018

【自動化】AppleScript 學習筆記

【自動化】AppleScript 學習筆記

輸出

簡單輸出

Code:

"Hello~"

Output:

Result:
"Hello"

log

Code:

log "Hello"

log 輸出的內容可在Messages Tab, Events Tab 或 Replies Tab中查看;Result Tab只會留存最後指定輸出的字串

Output:

(*Hello~*)

簡單輸出的方法只會留存最後指定輸出的字串,而log 則不會有這樣的問題

變量

set

Code:

set num to 10

log num

Output:

(*10*)

控制

tell

Code:

tell application "Finder" --指定Finder
	-- code here
end tell

display dialog

顯示對話框

Code:

display dialog "Hi"

Output:
img

say

播放語音

Code:

say "Hello"

if

Code:

set num to 100
if num > 99 then
	display dialog "Hi"
end if

Output:

img

if…else

set num to 10
if num > 99 then
	return "Hello"
else
	return "Bye"
end if

Output:
return 的內容顯示於Result tab

"Hello"

repeat

Code:
loop 10次

set num to 0
repeat until num = 10
	set num to (num + 1)
	log num
end repeat

Output:

(*1*)
(*2*)
(*3*)
(*4*)
(*5*)
(*6*)
(*7*)
(*8*)
(*9*)
(*10*)

do script

Code:
打開Terminal 並於Desktop建立Folder—FolderName: abcd

Terminal 指令:

cd ~/Desktop
mkdir abcd

Code:

’ & '用於連接字符串

tell application "Terminal"
	do script "cd ~/Desktop; " & "mkdir abcd"
end tell

activate

將應用程序啟動並置於最前
Code:

tell application "Terminal"
	activate
end tell

launch

如果應用程序未啟動,則啟動它,但不發送命令

Code:

tell application "Terminal"
	launch
end tell

delay

Code:

display dialog 1 buttons {"Next is dialog 2"} --設定button內容
delay 2 --等待2秒
display dialog "I'm dialog 2"

Output:

Delay 1

按下 ’Next is dialog 2’後

等待2 秒

Delay 2

quit

退出應用程式

Code:
打開Terminal 並放置到最前
輸入date 指令
等待 5秒
退出應用程式

tell application "Terminal"
	activate
	do script "date"
	delay 5
	quit
end tell

輸入

User Input

Code:

set myans to display dialog "1 + 1 = ?" default answer ""
set ans to text returned of myans
if ans = "2" then --從dialog取得的ans為字符串
	return "Right"
else
	return "Wrong"
end if

Output:

userInput1

輸入正確答案
Result:
"Right"
輸入錯誤答案
Result:
"Wrong"

注釋

AppleScript中注釋方法有兩種

--我是單行注釋
(*我
 是
 多
 行
 注
 釋*)

Reference

http://applescript.wikia.com/wiki/Wiki
https://developer.apple.com/library/archive/documentation/AppleScript/
http://downloads.techbarrack.com/books/programming/AppleScript/website/