022_applescript快速入门教程

基础语法

一、这部分介绍注释,发出声音,弹窗

(1)简单入门

<1>多行注释
(*
this is multi 
comment
*)
<2>发出响声
beep 3

(2)

#表示使用"Daniel"(英国发音)发出声音,人员选择如下图1所示
say "Hello,world" using "Daniel" --或用"--"也可以表示单行注释

              图1
(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                                                                        #获取弹出框输入的内容

        图1

 五、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所示

          图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所示

          图1

          图2

          图3

九、

可以通过词典来找相应的方法名称,将应用直接拖到 Dock 上的脚本编辑器图标,然后就会显示扩展的词典(如下图1),在这里可以查看该应用支持的相应方法名称说明,比如Iterm2的词典如下图2所示: 

    图1

              图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

  

Reference:

https://www.youtube.com/watch?v=Nf7sH38RZt4&index=8&list=PLWpwk5XqAMKzsofHtUGgx2wryVCYjc7ya

https://www.bggofurther.com/2017/01/iterm-automatic-mutliple-panes-with-applescript/

posted @ 2018-12-22 20:41  arun_yh  阅读(2254)  评论(0编辑  收藏  举报