如何在Cocoa中接收NSTask的输出?

Use*_*234 5 macos cocoa objective-c

我在我的Cocoa APP中使用NSTask,我需要能够获得结果,并将其存储在Array中,或者其他东西......我正在从APP执行终端命令,我需要输出它们.

NSString *path = @"/path/to/command";
NSArray *args = [NSArray arrayWithObjects:..., nil];
[[NSTask launchedTaskWithLaunchPath:path arguments:args] waitUntilExit];

//After task is finished , need output
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Jon*_*ess 16

您希望使用 - [NSTask setStandardOutput:]在启动任务之前将NSPipe附加到任务.管道包含两个文件句柄,任务将写入管道的一端,您将从另一端读取.您可以安排文件句柄来读取后台任务中的所有数据,并在完成后通知您.

它看起来像这样(在堆栈溢出中编译):

- (void)launch {
    NSTask *task = [[[NSTask alloc] init] autorelease];
    [task setLaunchPath:@"/path/to/command"];
    [task setArguments:[NSArray arrayWithObjects:..., nil]];
    NSPipe *outputPipe = [NSPipe pipe];
    [task setStandardOutput:outputPipe];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readCompleted:) name:NSFileHandleReadToEndOfFileCompletionNotification object:[outputPipe fileHandleForReading]];
    [[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotify];
    [task launch];
}

- (void)readCompleted:(NSNotification *)notification {
    NSLog(@"Read data: %@", [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem]);
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleReadToEndOfFileCompletionNotification object:[notification object]];
}
Run Code Online (Sandbox Code Playgroud)

如果您还想捕获标准错误的输出,则可以使用第二个管道和通知.