我知道如何将数据发送到任务:
NSData *charlieSendData = [[charlieImputText stringValue] dataUsingEncoding:NSUTF8StringEncoding];
[[[task standardInput] fileHandleForWriting] writeData:charlieSendData];
但是我如何得到任务响应的内容?
利亚
答案 0 :(得分:32)
将NSPipe
或NSFileHandle
作为任务的standardOutput
,并从中读取。
NSTask * list = [[NSTask alloc] init];
[list setLaunchPath:@"/bin/ls"];
[list setCurrentDirectoryPath:@"/"];
NSPipe * out = [NSPipe pipe];
[list setStandardOutput:out];
[list launch];
[list waitUntilExit];
[list release];
NSFileHandle * read = [out fileHandleForReading];
NSData * dataRead = [read readDataToEndOfFile];
NSString * stringRead = [[[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"output: %@", stringRead);
请注意,如果您使用管道,则必须担心管道填满。如果您提供NSFileHandle
,则任务可以输出所需的全部内容,而不必担心丢失任何内容,但您也需要将数据写入磁盘的开销。
答案 1 :(得分:4)
Swift 3解决方案,您可以实现一个接受FileHandle
let process = Process()
process.launchPath = launchPath
process.arguments = arguments
let stdOut = Pipe()
process.standardOutput = stdOut
let stdErr = Pipe()
process.standardError = stdErr
let handler = { (file: FileHandle!) -> Void in
let data = file.availableData
guard let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
else { return}
print(output.components(separatedBy: "\n").first!)
}
stdErr.fileHandleForReading.readabilityHandler = handler
stdOut.fileHandleForReading.readabilityHandler = handler
process.terminationHandler = { (task: Process?) -> () in
stdErr.fileHandleForReading.readabilityHandler = nil
stdOut.fileHandleForReading.readabilityHandler = nil
}
process.launch()
process.waitUntilExit()