NSTask的实时输出

aka*_*kyy 20 macos nstask

我有一个PHP脚本,它有mutliple sleep()命令.我想在我的应用程序中执行它NSTask.我的脚本看起来像这样:

echo "first\n"; sleep(1); echo "second\n"; sleep(1); echo "third\n";
Run Code Online (Sandbox Code Playgroud)

我可以使用通知异步执行我的任务:

- (void)awakeFromNib {
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/usr/bin/php"];

    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: @"-r", @"echo \"first\n\"; sleep(1); echo \"second\n\"; sleep(1); echo \"third\n\";", nil];
    [task setArguments: arguments];

    NSPipe *p = [NSPipe pipe];
    [task setStandardOutput:p];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskExited:) name:NSTaskDidTerminateNotification object:task];

    [task launch];

}

- (void)taskExited:(NSNotification *)notif {
    NSTask *task = [notif object];
    NSData *data = [[[task standardOutput] fileHandleForReading] readDataToEndOfFile];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"%@",str);
}
Run Code Online (Sandbox Code Playgroud)

我的输出是(当然2秒后):

2011-08-03 20:45:19.474 MyApp[3737:903] first
second
third
Run Code Online (Sandbox Code Playgroud)

我的问题是:如何在印刷后立即获得三个字?

ugh*_*fhw 23

waitForDataInBackgroundAndNotify当脚本将数据写入其输出时,您可以使用NSFileHandle的方法接收通知.但是,只有在解释器立即发送字符串时,这才有效.如果它缓冲输出,您将在任务退出后收到单个通知.

- (void)awakeFromNib {
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/usr/bin/php"];

    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: @"-r", @"echo \"first\n\"; sleep(1); echo \"second\n\"; sleep(1); echo \"third\n\";", nil];
    [task setArguments: arguments];

    NSPipe *p = [NSPipe pipe];
    [task setStandardOutput:p];
    NSFileHandle *fh = [p fileHandleForReading];
    [fh waitForDataInBackgroundAndNotify];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedData:) name:NSFileHandleDataAvailableNotification object:fh];

    [task launch];

}

- (void)receivedData:(NSNotification *)notif {
    NSFileHandle *fh = [notif object];
    NSData *data = [fh availableData];
    if (data.length > 0) { // if data is found, re-register for more data (and print)
        [fh waitForDataInBackgroundAndNotify];
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@" ,str);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我挣扎了一段时间后更新了代码.你需要另一个`waitForDataInBackgroundAndNotify`,而不是`readInBackgroundAndNotify`. (4认同)
  • 试着用`find`命令这个代码片断它创建长期结果和片段需要额外的`[FH waitForDataInBackgroundAndNotify]`为了得到完整的数据.希望这有助于像我这样的初学者. (3认同)

Ker*_*ers 9

作为参考,这里是ughoavgfhw在swift中的答案.

override func awakeFromNib() {
    // Setup the task
    let task = NSTask()
    task.launchPath = "/usr/bin/php"
    task.arguments = ["-r", "echo \"first\n\"; sleep(1); echo \"second\n\"; sleep(1); echo \"third\n\";"]

    // Pipe the standard out to an NSPipe, and set it to notify us when it gets data
    let pipe = NSPipe()
    task.standardOutput = pipe
    let fh = pipe.fileHandleForReading
    fh.waitForDataInBackgroundAndNotify()

    // Set up the observer function
    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self, selector: "receivedData:", name: NSFileHandleDataAvailableNotification, object: nil)

    // You can also set a function to fire after the task terminates
    task.terminationHandler = {task -> Void in
           // Handle the task ending here
    }

    task.launch()
}

func receivedData(notif : NSNotification) {
    // Unpack the FileHandle from the notification
    let fh:NSFileHandle = notif.object as NSFileHandle
    // Get the data from the FileHandle
    let data = fh.availableData
    // Only deal with the data if it actually exists
    if data.length > 1 {
    // Since we just got the notification from fh, we must tell it to notify us again when it gets more data
        fh.waitForDataInBackgroundAndNotify()
        // Convert the data into a string
        let string = NSString(data: data, encoding: NSASCIIStringEncoding)
        println(string!)
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您的任务在管道中产生大量输出,则此构造将是必需的.简单地调用pipe.fileHandleForReading.readDataToEndOfFile()将不起作用,因为任务正在等待管道被清空,因此它可以在程序等待数据结束时写入更多内容.因此,您的程序将挂起.此通知和观察者构造允许异步读取管道,从而防止上述僵局.