如何在OS X应用程序中获取shell脚本输出

时间:2016-02-15 13:51:35

标签: macos shell

我有一个OS X应用程序,它使用以下方法调用shell脚本:

@implementation ViewController {
    NSTask *task;
    NSPipe *pipe;
}

- (void)viewDidLoad {
   [super viewDidLoad];

    // Do any additional setup after loading the view.

    [self runCommand:[[NSBundle mainBundle] pathForResource:@"Test" ofType:@"command"] arguments:nil];
}

- (void)runCommand:(NSString *)cmd arguments:(NSArray *)args {
    if (task)
    {
        [task interrupt];

    }
    else
    {
        task = [[NSTask alloc] init];
        [task setLaunchPath:cmd];

        [task setArguments:args];

        pipe = [[NSPipe alloc] init];
        [task setStandardOutput:pipe];

        NSFileHandle* fh = [pipe fileHandleForReading];

        [task launch];
        [fh readInBackgroundAndNotify];
    }
}

@end

shell脚本Test.command具有输出文本,当您在终端中执行它时,它将显示在终端窗口中,但有没有办法在我的OS X App中检索此输出并将其显示到文本视图中?

1 个答案:

答案 0 :(得分:1)

您需要观察任务触发的通知事件。注册观察者并启动命令的顺序也很重要。尝试类似:

{
    task = [[NSTask alloc] init];
    [task setLaunchPath:cmd];
    [task setArguments:args];

    pipe = [[NSPipe alloc] init];
    [task setStandardOutput:pipe];

    // Observe events before launching the task, otherwise the execution
    // might end before we get the chance to register the observer.
    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(didCompleteReadingFileHandle:) 
        name:NSFileHandleReadCompletionNotification 
        object:[[task standardOutput] fileHandleForReading]];

    // Make it start reading before launching.
    [[pipe fileHandleForReading] readInBackgroundAndNotify];

    // Launch it.
    [task launch];
}

- (void)didCompleteReadingFileHandle:(NSNotification *)notification
{
    NSData *data = [[notification userInfo]
        objectForKey:NSFileHandleNotificationDataItem];

    // Do something with data...
}