如何接收NSTask的输出在Cocoa? [英] How to receive output of NSTask in Cocoa?

查看:785
本文介绍了如何接收NSTask的输出在Cocoa?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using NSTask in my Cocoa APP , and I need to be able to get result, and store it in Array, or something... I'm executing terminal commands from APP, and I need outputs for them.

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

//After task is finished , need output

推荐答案

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

You want to use -[NSTask setStandardOutput:] to attach an NSPipe to the task before launching it. A pipe holds two file handles, the task will write to one end of the pipe, and you'll read from the other. You can schedule the file handle to read all of the data from the background task and notify you when it's complete.

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

It will look something like this (compiled in stack overflow):

- (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]];
}

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

If you also want to capture the output of standard error, you can use a second pipe and notification.

这篇关于如何接收NSTask的输出在Cocoa?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆