[問題] NSTask & whereis

看板MacDev作者 (狗狗)時間13年前 (2012/03/06 20:00), 編輯推噓3(305)
留言8則, 3人參與, 最新討論串1/1
最近再練習寫一個小的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
話說這問題本身就很有教學性..推一個(Y)
03/07 00:10, 2F

03/07 01:00, , 3F
我猜想應該是EOF的符號,可是我不知道怎麼檢查 XD
03/07 01:00, 3F

03/07 01:00, , 4F
因為NSLog看不出來.. Orz
03/07 01:00, 4F

03/07 01:47, , 5F
NSString 轉NSData 印Hex 就可以看結尾了
03/07 01:47, 5F

03/07 02:24, , 6F
NSLog(@"Hex Value: %x", [s characterAtIndex:i]);如何?
03/07 02:24, 6F

03/07 02:25, , 7F
NSString* s=@"123456";
03/07 02:25, 7F

03/07 10:48, , 8F
謝謝兩位,結果是A: NL line feed, new line
03/07 10:48, 8F
文章代碼(AID): #1FLVnPbm (MacDev)
文章代碼(AID): #1FLVnPbm (MacDev)