使用Swift实时NSTask输出到NSTextView

时间:2015-04-09 20:55:18

标签: swift nstextview nstask

我正在使用NSTask来运行rsync,我希望状态显示在窗口内滚动视图的文本视图中。现在我有这个:

let pipe = NSPipe()
task2.standardOutput = pipe
task2.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSASCIIStringEncoding)! as String

textView.string = output

这就是关于转移的一些统计数据,但是我想实时获得输出,比如当我在Xcode中运行应用程序时打印出来的内容,并将其放入文本视图中。有没有办法做到这一点?

4 个答案:

答案 0 :(得分:22)

自macOS 10.7起,readabilityHandler上的NSPipe属性也可用于设置新数据可用时的回调:

let task = NSTask()

task.launchPath = "/bin/sh"
task.arguments = ["-c", "echo 1 ; sleep 1 ; echo 2 ; sleep 1 ; echo 3 ; sleep 1 ; echo 4"]

let pipe = NSPipe()
task.standardOutput = pipe
let outHandle = pipe.fileHandleForReading

outHandle.readabilityHandler = { pipe in
    if let line = String(data: pipe.availableData, encoding: NSUTF8StringEncoding) {
        // Update your view with the new text here
        print("New ouput: \(line)")
    } else {
        print("Error decoding data: \(pipe.availableData)")
    }
}

task.launch()

我很惊讶没有人提到这一点,因为它更简单。

答案 1 :(得分:15)

(有关Swift 3/4的更新,请参阅Patrick F.'s answer。)

您可以使用通知从管道异步读取。 这是一个简单的例子,展示它是如何工作的,希望如此 帮助您入门:

let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "echo 1 ; sleep 1 ; echo 2 ; sleep 1 ; echo 3 ; sleep 1 ; echo 4"]

let pipe = NSPipe()
task.standardOutput = pipe
let outHandle = pipe.fileHandleForReading
outHandle.waitForDataInBackgroundAndNotify()

var obs1 : NSObjectProtocol!
obs1 = NSNotificationCenter.defaultCenter().addObserverForName(NSFileHandleDataAvailableNotification,
    object: outHandle, queue: nil) {  notification -> Void in
        let data = outHandle.availableData
        if data.length > 0 {
            if let str = NSString(data: data, encoding: NSUTF8StringEncoding) {
                print("got output: \(str)")
            }
            outHandle.waitForDataInBackgroundAndNotify()
        } else {
            print("EOF on stdout from process")
            NSNotificationCenter.defaultCenter().removeObserver(obs1)
        }
}

var obs2 : NSObjectProtocol!
obs2 = NSNotificationCenter.defaultCenter().addObserverForName(NSTaskDidTerminateNotification,
    object: task, queue: nil) { notification -> Void in
        print("terminated")
        NSNotificationCenter.defaultCenter().removeObserver(obs2)
}

task.launch()

您可以追加收到的print("got output: \(str)")而不是{{1}} 字符串到您的文本视图。

上面的代码假定runloop处于活动状态(情况就是如此) 在默认的Cocoa应用程序中)。

答案 2 :(得分:8)

这是Martin在最新版本的Swift上面的答案的更新版本。

    let task = Process()
    task.launchPath = "/bin/sh"
    task.arguments = ["-c", "echo 1 ; sleep 1 ; echo 2 ; sleep 1 ; echo 3 ; sleep 1 ; echo 4"]

    let pipe = Pipe()
    task.standardOutput = pipe
    let outHandle = pipe.fileHandleForReading
    outHandle.waitForDataInBackgroundAndNotify()

    var obs1 : NSObjectProtocol!
    obs1 = NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable,
       object: outHandle, queue: nil) {  notification -> Void in
        let data = outHandle.availableData
        if data.count > 0 {
            if let str = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
                print("got output: \(str)")
            }
            outHandle.waitForDataInBackgroundAndNotify()
        } else {
            print("EOF on stdout from process")
            NotificationCenter.default.removeObserver(obs1)
        }
    }

    var obs2 : NSObjectProtocol!
    obs2 = NotificationCenter.default.addObserver(forName: Process.didTerminateNotification,
               object: task, queue: nil) { notification -> Void in
                print("terminated")
                NotificationCenter.default.removeObserver(obs2)
        }
    task.launch()

答案 3 :(得分:2)

基于readabilityHandler,我有一个答案比通知方法更干净。在Swift 5中就是这样:

class ProcessViewController: NSViewController {

     var executeCommandProcess: Process!

     func executeProcess() {

     DispatchQueue.global().async {


           self.executeCommandProcess = Process()
           let pipe = Pipe()

           self.executeCommandProcess.standardOutput = pipe
           self.executeCommandProcess.launchPath = ""
           self.executeCommandProcess.arguments = []
           var bigOutputString: String = ""

           pipe.fileHandleForReading.readabilityHandler = { (fileHandle) -> Void in
               let availableData = fileHandle.availableData
               let newOutput = String.init(data: availableData, encoding: .utf8)
               bigOutputString.append(newOutput!)
               print("\(newOutput!)")
               // Display the new output appropriately in a NSTextView for example

           }

           self.executeCommandProcess.launch()
           self.executeCommandProcess.waitUntilExit()

           DispatchQueue.main.async {
                // End of the Process, give feedback to the user.
           }

     }
   }

}

请注意,Process必须是一个属性,因为在上面的示例中,鉴于命令在后台执行,因此,如果它是局部变量,则将立即释放该进程。感谢您的关注。