當前位置:
首頁 > 知識 > OSx AppleScript簡單入門

OSx AppleScript簡單入門

引言

大家都知道,osx是基於Unix內核由蘋果公司開發的一款操作系統,而unix內核本身會提供類似於bash的各種shell以供用戶去選擇使用,osx當然很好的支持了uinx的shell,同時,osx也有自己特有的級別比較高的腳本語言AppleScript,那麼我們今天就來一起學習一下


簡介

AppleScript是蘋果公司開發的一種腳本語言,可以用來控制運行於Mac OS上的程序,也可以寫成獨立運行的Applet。

目前在網上的相關資料並不是很全,所以我們只能一步一步自己去摸索,有不當之處還請批評指正


AppleScript的優勢

1.簡單

AppleScript 雖然是一種腳本語言,但是是一種接近自然語言的腳本語言。即使沒有計算機基礎,在閱讀文檔和幾個實例腳本之後,就能動手寫出實用的腳本工具。

第一個applescript腳本

1.點擊launchpad圖標,找到script Editor

2.選擇文件路徑

3.打開了一個文本編輯器

下面,我們就要在這個編輯器中進行寫作

OSx AppleScript簡單入門

我們先寫一段簡單的腳本


say "hello world"

你沒有看錯,只有這一句,上面的代碼就是讓計算機發聲。大家可以親自試一下,哦對了,忘了告訴大家怎麼運行了,我們先學習一下快捷鍵


基本操作:

command+k ---> 編譯

command+r ---> 運行

control+點擊編輯區上半部分 ---> 提示

幾個使用的例子

提取 Crash ID

AppleScript 的另一個強大之處是可以和系統自帶的各類常用命令行工具(比如 grep,sed,awk 等)交互,這意味著對文本和文件的操作可以遊刃有餘。下面的代碼是通過 sed 工具來提取郵件中的 Crash ID:


tell application "Microsoft Outlook"

set theMessages to messages of folder "iOS-Crash" of default account

set crash_id_set to {}

repeat with theMessage in theMessages

set msgContent to plain text content of theMessage

tell me to set crash_id to do shell script "echo " & quoted form of msgContent & " | sed -E -n "s_.* crash_id:(.+)}_\1_1p""

if crash_id is not in crash_id_set and the length of crash_id > 0 then

set crash_id_set to crash_id_set & crash_id

end if

end repeat

end tell

tell application "Finder"
empty the trash
end tell

上面的代碼是調用Finder程序,調用的過程為清空回收站。

tell關鍵字調用程序,end tell 結束調用。很多新手這裡忘記end tell結束調用。


基本操作

對於變數的操作

AppleScript 定義變數

set x to 30

這裡,就設置了一個x變數,存儲著30這個值。

彈窗操作

set stringToBeDispalyed to "hi applescript"
display dialog "stringToBeDisplayed"
display dialog stringToBeDispalyed

OSx AppleScript簡單入門

OSx AppleScript簡單入門

運行結果

注釋


與c語言區別不大

-- 注釋一行

# 注釋一行

(???) 注釋多行

錯誤捕獲

意外的終止是我們所不希望的。比如,你的腳本需要打開一個文件夾處理其中的文件, 但是這個文件夾已經被刪除了,你會希望腳本允許用戶選擇其它合適的文件夾,而不是意外退出。

你可以把這些可能引起運行錯

誤的語句放入「try...end try」模塊中

try
set x to 1 / 0
on error the error_message number the error_number
display dialog "Error: " & the error_number & "." & the error_message buttons {"OK"}
end try

變數轉型

那麼number對你真的一點挑戰性都沒有。

OSx AppleScript簡單入門

數值類型

字元串也都是變數,它們是可以用&拼接的,還有一些其他的玩法。

OSx AppleScript簡單入門

字元串之一

OSx AppleScript簡單入門

字元串之二

分割,組合,轉化,字元串的玩法還是蠻多的。

list的使用和數組一樣,就是增,刪,改,查

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 青峰科技 的精彩文章:

DHCP的原理與應用
華為路由器配置RIP路由協議全攻略

TAG:青峰科技 |