作者leondemon (狗狗)
看板MacDev
标题[问题] NSTask & whereis
时间Tue Mar 6 20:00:23 2012
最近再练习写一个小的library,方便用Objective-C下Shell指令
NSTask需要一个launchPath来执行指令
於是我利用了Shell的whereis来查找其他指令的path
但是却发生奇怪的事情... 请看下面范例
1)
先帮NSTask开了Category,然後加入下面两个method
//利用block设定NSTask相关的设定,然後会自动执行该task
typedef void (^TaskBlock)(NSTask*);
+ (NSTask*) performTask:(TaskBlock) taskBuild{
NSTask *task = [[NSTask alloc] init];
task.standardOutput = [NSPipe pipe];
taskBuild(task);
[task launch];
return task;
}
//快速取得回传的字串
- (NSString*) readOutput{
NSString *output;
NSFileHandle* handle = [self.standardOutput fileHandleForReading];
NSData *data = [handle readDataToEndOfFile];
output = [[NSString alloc] initWithData:data
encoding:NSISOLatin1StringEncoding];
return output;
}
2)
利用上面的Category进行下面操作
NSString *whereisPath = @"/usr/bin/whereis";
NSTask *task = [NSTask performTask:^(NSTask *task){
task.launchPath = whereisPath;
task.arguments = [NSArray arrayWithObjects:@"git", nil];
}];
NSString *taskOutput = [task readOutput];
NSLog(@"%@", taskOutput);
console log => /usr/bin/git
然後利用这个获得的path接着执行下面git的操作
NSTask *git = [NSTask performTask:^(NSTask *task){
task.launchPath = taskOutput;
task.arguments = [NSArray arrayWithObjects:@"status", nil];
}];
NSString *gitOutput = [git readOutput];
NSLog(@"%@", gitOutput);
console log => launch path not accessible
获得的结果告知该path不能使用 於是我做了以下的检查
NSString *gitPath = @"/usr/bin/git";
if ([taskOutput isEqualToString:gitPath]) {
NSLog(@"the same path string");
}else{
NSLog(@"not equal to the path string");
}
NSLog(@"%lu", [taskOutput length]);
NSLog(@"%lu", [gitPath length]);
console log => not equal to the path string
console log => 13
console log => 12
发现task回传的output多出一个字元
然後如下把taskoutput删除最後一个字元後 之前的code就可以跑了
taskOutput = [taskOutput substringToIndex:[taskOutput length]-1];
想问一下这多出的字元是单纯的一个space吗?
还是跟data的EndOfFile有关?有什麽有效率的去除方式吗?
如果我每次都把whereis 的output删除最後一个字元拿来当做launchPath,这样可以吗?
测试过 stringByStandardizingPath这个方法,不过似乎不能帮我处理那个字元...
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 111.80.29.129
※ 编辑: leondemon 来自: 111.80.29.129 (03/06 20:05)
1F:推 Piceman:先检查那个字元是什麽字? 03/07 00:10
2F:→ Piceman:话说这问题本身就很有教学性..推一个(Y) 03/07 00:10
3F:→ leondemon:我猜想应该是EOF的符号,可是我不知道怎麽检查 XD 03/07 01:00
4F:→ leondemon:因为NSLog看不出来.. Orz 03/07 01:00
5F:推 appleway:NSString 转NSData 印Hex 就可以看结尾了 03/07 01:47
6F:推 Piceman:NSLog(@"Hex Value: %x", [s characterAtIndex:i]);如何? 03/07 02:24
7F:→ Piceman:NSString* s=@"123456"; 03/07 02:25
8F:→ leondemon:谢谢两位,结果是A: NL line feed, new line 03/07 10:48