OC调用Shell脚本

AppleScript

AppleScript是Mac OS X上的脚本语言,写好的脚本语言可以使用NSTask执行,而脚本本身可以做很多事情。
编译器自带的Apple Script Editor就在应用程序下面,打开以后界面很简单,左上角四个键,录制,停止,运行,编译.中间是代码框,最下面是描述和系统的日志输出。
脚本文件语法也不需要我们学,直接照着例子来就行

示例1 让系统嗡一下

AppleScript代码

1
beep

敲完运行,需要主语的是除了关键字和引号内部的字符,其他都不需要注意大小写,运行的时候会帮你格式化好

示例2 清除废纸篓

AppleScript代码

1
2
3
4
5
tell application "Finder"
empty the trash
end tell

tell application是呼唤程序,然后程序卸载引号内,即让程序做什么,end tell是对程序的调用结束。empty the trash是finder的专属操作。

但是在项目中用到最多的还是直接调用shell的特性,其实一句话就完事

AppleScript代码

1
do shell script "example A"
需要注意的是,AppleScript默认的shell是去找/bin/sh(在xcode里面创建shell文件头文件也可以看到),而我们的终端则是/bin/bash,可能会出现在终端中可以运行,脚本中却说找不到命令的情况

编译器的特点 应用程序可以替换

AppleScript代码

1
tell application "Yaphets"

明显Yaphets在计算机上是找不到的,那么这时候会跳出窗口让你选择Yaphets代表的程序,并且替换,后续编写使用Yaphets会自动选择你刚刚替换的程序,而且下次打开编译器仍然保持

设置变量 set 规则和c类似

AppleScript代码

1
set picPath to "/documents"

定义以后,后续文本可以使用,也可以修改
AppleScript代码

1
2
3
4
5
6
7
8
set DDd to 1
set DDd to "Hello world"
set aaa to DDd
display dialog aaa
display dialog DDd
set DDd to 1
display dialog aaa
display dialog DDd

dispaly dialog 会用一个对话框显示输出,拼接字符串用&

程序调用脚本

首先我们可以用NSAppleScript类直接运行脚本,可以用源码也可以用文件的形式,而且文件可以是源码也可以是编译好的

AppleScript代码

1
set i to 100

那么这里的脚本值就是100

  • 普通类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
NSAppleEventDescriptor *eventDescriptor = nil;
NSAppleScript *script = nil;
NSBundle *bunlde = [NSBundle mainBundle];
NSString *scriptPath = [bunlde pathForResource:@"demo"
ofType:@"scpt"
inDirectory:nil];
if (scriptPath)
{
script = [[NSAppleScirpt alloc] initWithContentsOfURL:[NSURL fileURLWithPath:scriptPath] error:nil];
if (script)
{
eventDescriptor = [script executeAndReturnError:nil];
if (eventDescriptor)
{
NSLog(@"%@", [eventDescriptor stringValue]);
}
}
}

这是最简单的返回值,如果返回值是list(NSArray)或者record(NSDictionary),需要更加麻烦一点

  • list 类型
1
2
3
4
5
6
7
NSAppleEventDescriptor *e = [NSTask gtm_runAppleScript:@"value"];
int count = [e numberOfItems];
for (int i = 1; i <= count; i++)
{
NSAppleEventDescriptor *d = [e descriptorAtIndex:i];
NSLog(@"%@", [d stringValue]);
}
  • record类型

AppleScript代码

1
{key1:1, key2:2, key3:3}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
NSAppleEventDescriptor *e = [NSTask gtm_runAppleScript:@"value"];
// 其实就返回一个record的话,count就是1
int count = [e numberOfItems];
for (int i = 1; i <= count; i++)
{
NSAppleEventDescriptor *d = [e descriptorAtIndex:i];
// 这里会是6条
int items = [d numberOfItems];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
for (int j = 1; j <= items; j +=2)
{
// 前一条是key的名字
NSAppleEventDescriptor *dKey = [d descriptorAtIndex:j];
NSString *key = [dKey stringValue];
// 后一条是对应的值
NSAppleEventDescriptor *dValue = [d descriptorAtIndex:j+1];
NSString *value = [dValue stringValue];
[dic setObject:value forKey:key];
}
}
这个人很帅<br>他什么都不想说<br>