[問題] NSTask & whereis
最近再練習寫一個小的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)
推
03/07 00:10, , 1F
03/07 00:10, 1F
→
03/07 00:10, , 2F
03/07 00:10, 2F
→
03/07 01:00, , 3F
03/07 01:00, 3F
→
03/07 01:00, , 4F
03/07 01:00, 4F
推
03/07 01:47, , 5F
03/07 01:47, 5F
推
03/07 02:24, , 6F
03/07 02:24, 6F
→
03/07 02:25, , 7F
03/07 02:25, 7F
→
03/07 10:48, , 8F
03/07 10:48, 8F
MacDev 近期熱門文章
PTT數位生活區 即時熱門文章