2010-08-09 84 views

回答

26

舉一個NSPipeNSFileHandle作爲任務的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,則該任務可以輸出所需的所有內容,而不必擔心會丟失任何內容,但是也會產生必須將數據寫入磁盤的開銷。

+0

我已經做封閉。 [任務標準輸出] - 如果我只是調用它,它會給出輸出嗎? – objectiveccoder001 2010-08-09 19:21:17

+0

@Elijah默認情況下,沒有。如果你想輸出,你必須在啓動任務之前提供一個管道或文件句柄,然後開始從文件句柄(或者'[pipe fileHandleForReading]')中讀取數據以獲取數據。 (它會給你'NSData'對象,而不是字符串或任何東西) – 2010-08-09 19:38:47

+0

你能舉個例子嗎? – objectiveccoder001 2010-08-09 20:04:42

0

斯威夫特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()