【问题标题】:How to receive output of NSTask in Cocoa?如何在 Cocoa 中接收 NSTask 的输出?
【发布时间】:2011-12-03 17:04:54
【问题描述】:

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

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

//After task is finished , need output

非常感谢!

【问题讨论】:

  • 你需要考虑使用NSPipe
  • 好的,谢谢。我尝试使用它,但无法获得输出。可能错过了什么
  • 是的。我自己不需要使用它,所以我不知道它的具体情况。看这里可能会让你开始:cocoadev.com/index.pl?NSPipe
  • 好的,谢谢。会试着弄清楚。我只是 Cocoa 的新手

标签: objective-c macos cocoa


【解决方案1】:

您想在启动任务之前使用 -[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]];
}

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
  • 2013-05-30
  • 2019-11-28
相关资源
最近更新 更多